Home | History | Annotate | Line # | Download | only in cp
      1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
      2    Copyright (C) 1992-2024 Free Software Foundation, Inc.
      3    Written by Ken Raeburn (raeburn (at) cygnus.com) while at Watchmaker Computing.
      4    Rewritten by Jason Merrill (jason (at) cygnus.com).
      5 
      6 This file is part of GCC.
      7 
      8 GCC is free software; you can redistribute it and/or modify
      9 it under the terms of the GNU General Public License as published by
     10 the Free Software Foundation; either version 3, or (at your option)
     11 any later version.
     12 
     13 GCC is distributed in the hope that it will be useful,
     14 but WITHOUT ANY WARRANTY; without even the implied warranty of
     15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     16 GNU General Public License for more details.
     17 
     18 You should have received a copy of the GNU General Public License
     19 along with GCC; see the file COPYING3.  If not see
     20 <http://www.gnu.org/licenses/>.  */
     21 
     22 /* Known bugs or deficiencies include:
     23 
     24      all methods must be provided in header files; can't use a source
     25      file that contains only the method templates and "just win".
     26 
     27      Fixed by: C++20 modules.  */
     28 
     29 #include "config.h"
     30 #define INCLUDE_ALGORITHM // for std::equal
     31 #include "system.h"
     32 #include "coretypes.h"
     33 #include "cp-tree.h"
     34 #include "timevar.h"
     35 #include "stringpool.h"
     36 #include "varasm.h"
     37 #include "attribs.h"
     38 #include "stor-layout.h"
     39 #include "intl.h"
     40 #include "c-family/c-objc.h"
     41 #include "cp-objcp-common.h"
     42 #include "toplev.h"
     43 #include "tree-iterator.h"
     44 #include "type-utils.h"
     45 #include "gimplify.h"
     46 #include "gcc-rich-location.h"
     47 #include "selftest.h"
     48 #include "target.h"
     49 #include "builtins.h"
     50 #include "omp-general.h"
     51 
     52 /* The type of functions taking a tree, and some additional data, and
     53    returning an int.  */
     54 typedef int (*tree_fn_t) (tree, void*);
     55 
     56 /* The PENDING_TEMPLATES is a list of templates whose instantiations
     57    have been deferred, either because their definitions were not yet
     58    available, or because we were putting off doing the work.  */
     59 struct GTY ((chain_next ("%h.next"))) pending_template
     60 {
     61   struct pending_template *next;
     62   struct tinst_level *tinst;
     63 };
     64 
     65 static GTY(()) struct pending_template *pending_templates;
     66 static GTY(()) struct pending_template *last_pending_template;
     67 
     68 int processing_template_parmlist;
     69 static int template_header_count;
     70 
     71 static vec<int> inline_parm_levels;
     72 
     73 static GTY(()) struct tinst_level *current_tinst_level;
     74 
     75 static GTY(()) vec<tree, va_gc> *saved_access_scope;
     76 
     77 /* Live only within one (recursive) call to tsubst_expr.  We use
     78    this to pass the statement expression node from the STMT_EXPR
     79    to the EXPR_STMT that is its result.  */
     80 static tree cur_stmt_expr;
     81 
     82 // -------------------------------------------------------------------------- //
     83 // Local Specialization Stack
     84 //
     85 // Implementation of the RAII helper for creating new local
     86 // specializations.
     87 local_specialization_stack::local_specialization_stack (lss_policy policy)
     88   : saved (local_specializations)
     89 {
     90   if (policy == lss_nop)
     91     ;
     92   else if (policy == lss_blank || !saved)
     93     local_specializations = new hash_map<tree, tree>;
     94   else
     95     local_specializations = new hash_map<tree, tree>(*saved);
     96 }
     97 
     98 local_specialization_stack::~local_specialization_stack ()
     99 {
    100   if (local_specializations != saved)
    101     {
    102       delete local_specializations;
    103       local_specializations = saved;
    104     }
    105 }
    106 
    107 /* True if we've recursed into fn_type_unification too many times.  */
    108 static bool excessive_deduction_depth;
    109 
    110 struct spec_hasher : ggc_ptr_hash<spec_entry>
    111 {
    112   static hashval_t hash (tree, tree);
    113   static hashval_t hash (spec_entry *);
    114   static bool equal (spec_entry *, spec_entry *);
    115 };
    116 
    117 /* The general template is not in these tables.  */
    118 typedef hash_table<spec_hasher> spec_hash_table;
    119 static GTY (()) spec_hash_table *decl_specializations;
    120 static GTY (()) spec_hash_table *type_specializations;
    121 
    122 /* Contains canonical template parameter types. The vector is indexed by
    123    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
    124    TREE_LIST, whose TREE_VALUEs contain the canonical template
    125    parameters of various types and levels.  */
    126 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
    127 
    128 #define UNIFY_ALLOW_NONE 0
    129 #define UNIFY_ALLOW_MORE_CV_QUAL 1
    130 #define UNIFY_ALLOW_LESS_CV_QUAL 2
    131 #define UNIFY_ALLOW_DERIVED 4
    132 #define UNIFY_ALLOW_INTEGER 8
    133 #define UNIFY_ALLOW_OUTER_LEVEL 16
    134 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
    135 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
    136 
    137 enum template_base_result {
    138   tbr_incomplete_type,
    139   tbr_ambiguous_baseclass,
    140   tbr_success
    141 };
    142 
    143 static bool resolve_overloaded_unification (tree, tree, tree, tree,
    144 					    unification_kind_t, int,
    145 					    bool);
    146 static int try_one_overload (tree, tree, tree, tree, tree,
    147 			     unification_kind_t, int, bool, bool);
    148 static int unify (tree, tree, tree, tree, int, bool);
    149 static void add_pending_template (tree);
    150 static tree reopen_tinst_level (struct tinst_level *);
    151 static tree tsubst_initializer_list (tree, tree);
    152 static tree get_partial_spec_bindings (tree, tree, tree);
    153 static void tsubst_enum	(tree, tree, tree);
    154 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
    155 static int check_non_deducible_conversion (tree, tree, unification_kind_t, int,
    156 					   struct conversion **, bool, bool);
    157 static int maybe_adjust_types_for_deduction (tree, unification_kind_t,
    158 					     tree*, tree*, tree);
    159 static int type_unification_real (tree, tree, tree, const tree *,
    160 				  unsigned int, int, unification_kind_t,
    161 				  vec<deferred_access_check, va_gc> **,
    162 				  bool);
    163 static void note_template_header (int);
    164 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
    165 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
    166 static tree convert_template_argument (tree, tree, tree,
    167 				       tsubst_flags_t, int, tree);
    168 static tree for_each_template_parm (tree, tree_fn_t, void*,
    169 				    hash_set<tree> *, bool, tree_fn_t = NULL);
    170 static tree expand_template_argument_pack (tree);
    171 static tree build_template_parm_index (int, int, int, tree, tree);
    172 static bool inline_needs_template_parms (tree, bool);
    173 static void push_inline_template_parms_recursive (tree, int);
    174 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
    175 static int mark_template_parm (tree, void *);
    176 static int template_parm_this_level_p (tree, void *);
    177 static tree tsubst_friend_function (tree, tree);
    178 static tree tsubst_friend_class (tree, tree);
    179 static int can_complete_type_without_circularity (tree);
    180 static tree get_bindings (tree, tree, tree, bool);
    181 static int template_decl_level (tree);
    182 static int check_cv_quals_for_unify (int, tree, tree);
    183 static int unify_pack_expansion (tree, tree, tree,
    184 				 tree, unification_kind_t, bool, bool);
    185 static tree copy_template_args (tree);
    186 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
    187 static void tsubst_each_template_parm_constraints (tree, tree, tsubst_flags_t);
    188 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
    189 static tree tsubst_aggr_type_1 (tree, tree, tsubst_flags_t, tree, int);
    190 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
    191 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
    192 static bool check_specialization_scope (void);
    193 static tree process_partial_specialization (tree);
    194 static enum template_base_result get_template_base (tree, tree, tree, tree,
    195 						    bool , tree *);
    196 static tree try_class_unification (tree, tree, tree, tree, bool);
    197 static bool class_nttp_const_wrapper_p (tree t);
    198 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
    199 					   tree, tree);
    200 static bool template_template_parm_bindings_ok_p (tree, tree);
    201 static void tsubst_default_arguments (tree, tsubst_flags_t);
    202 static tree for_each_template_parm_r (tree *, int *, void *);
    203 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
    204 static void copy_default_args_to_explicit_spec (tree);
    205 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
    206 static bool dependent_template_arg_p (tree);
    207 static bool dependent_type_p_r (tree);
    208 static tree tsubst_stmt (tree, tree, tsubst_flags_t, tree);
    209 static tree tsubst_decl (tree, tree, tsubst_flags_t, bool = true);
    210 static tree tsubst_scope (tree, tree, tsubst_flags_t, tree);
    211 static tree tsubst_name (tree, tree, tsubst_flags_t, tree);
    212 static void perform_instantiation_time_access_checks (tree, tree);
    213 static tree listify (tree);
    214 static tree listify_autos (tree, tree);
    215 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
    216 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
    217 static tree get_underlying_template (tree);
    218 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
    219 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
    220 static tree make_argument_pack (tree);
    221 static tree enclosing_instantiation_of (tree tctx);
    222 static void instantiate_body (tree pattern, tree args, tree d, bool nested);
    223 static tree maybe_dependent_member_ref (tree, tree, tsubst_flags_t, tree);
    224 static void mark_template_arguments_used (tree, tree);
    225 static bool uses_outer_template_parms (tree);
    226 static tree alias_ctad_tweaks (tree, tree);
    227 static tree inherited_ctad_tweaks (tree, tree, tsubst_flags_t);
    228 static tree deduction_guides_for (tree, bool&, tsubst_flags_t);
    229 
    230 /* Make the current scope suitable for access checking when we are
    231    processing T.  T can be FUNCTION_DECL for instantiated function
    232    template, VAR_DECL for static member variable, or TYPE_DECL for
    233    for a class or alias template (needed by instantiate_decl).  */
    234 
    235 void
    236 push_access_scope (tree t)
    237 {
    238   gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
    239 	      || TREE_CODE (t) == TYPE_DECL);
    240 
    241   if (DECL_FRIEND_CONTEXT (t))
    242     push_nested_class (DECL_FRIEND_CONTEXT (t));
    243   else if (DECL_IMPLICIT_TYPEDEF_P (t)
    244 	   && CLASS_TYPE_P (TREE_TYPE (t)))
    245     push_nested_class (TREE_TYPE (t));
    246   else if (DECL_CLASS_SCOPE_P (t))
    247     push_nested_class (DECL_CONTEXT (t));
    248   else if (deduction_guide_p (t) && DECL_ARTIFICIAL (t))
    249     /* An artificial deduction guide should have the same access as
    250        the constructor.  */
    251     push_nested_class (TREE_TYPE (TREE_TYPE (t)));
    252   else
    253     push_to_top_level ();
    254 
    255   if (TREE_CODE (t) == FUNCTION_DECL)
    256     {
    257       vec_safe_push (saved_access_scope, current_function_decl);
    258       current_function_decl = t;
    259     }
    260 }
    261 
    262 /* Restore the scope set up by push_access_scope.  T is the node we
    263    are processing.  */
    264 
    265 void
    266 pop_access_scope (tree t)
    267 {
    268   if (TREE_CODE (t) == FUNCTION_DECL)
    269     current_function_decl = saved_access_scope->pop();
    270 
    271   if (DECL_FRIEND_CONTEXT (t)
    272       || (DECL_IMPLICIT_TYPEDEF_P (t)
    273 	  && CLASS_TYPE_P (TREE_TYPE (t)))
    274       || DECL_CLASS_SCOPE_P (t)
    275       || (deduction_guide_p (t) && DECL_ARTIFICIAL (t)))
    276     pop_nested_class ();
    277   else
    278     pop_from_top_level ();
    279 }
    280 
    281 /* Do any processing required when DECL (a member template
    282    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
    283    to DECL, unless it is a specialization, in which case the DECL
    284    itself is returned.  */
    285 
    286 tree
    287 finish_member_template_decl (tree decl)
    288 {
    289   if (decl == error_mark_node)
    290     return error_mark_node;
    291 
    292   gcc_assert (DECL_P (decl));
    293 
    294   if (TREE_CODE (decl) == TYPE_DECL)
    295     {
    296       tree type;
    297 
    298       type = TREE_TYPE (decl);
    299       if (type == error_mark_node)
    300 	return error_mark_node;
    301       if (MAYBE_CLASS_TYPE_P (type)
    302 	  && CLASSTYPE_TEMPLATE_INFO (type)
    303 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
    304 	{
    305 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
    306 	  check_member_template (tmpl);
    307 	  return tmpl;
    308 	}
    309       return NULL_TREE;
    310     }
    311   else if (TREE_CODE (decl) == FIELD_DECL)
    312     error_at (DECL_SOURCE_LOCATION (decl),
    313 	      "data member %qD cannot be a member template", decl);
    314   else if (DECL_TEMPLATE_INFO (decl))
    315     {
    316       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
    317 	{
    318 	  check_member_template (DECL_TI_TEMPLATE (decl));
    319 	  return DECL_TI_TEMPLATE (decl);
    320 	}
    321       else
    322 	return NULL_TREE;
    323     }
    324   else
    325     error_at (DECL_SOURCE_LOCATION (decl),
    326 	      "invalid member template declaration %qD", decl);
    327 
    328   return error_mark_node;
    329 }
    330 
    331 /* Create a template info node.  */
    332 
    333 tree
    334 build_template_info (tree template_decl, tree template_args)
    335 {
    336   tree result = make_node (TEMPLATE_INFO);
    337   TI_TEMPLATE (result) = template_decl;
    338   TI_ARGS (result) = template_args;
    339   return result;
    340 }
    341 
    342 /* DECL_TEMPLATE_INFO, if applicable, or NULL_TREE.  */
    343 
    344 static tree
    345 decl_template_info (const_tree decl)
    346 {
    347   /* This needs to match template_info_decl_check.  */
    348   if (DECL_LANG_SPECIFIC (decl))
    349     switch (TREE_CODE (decl))
    350       {
    351       case FUNCTION_DECL:
    352 	if (DECL_THUNK_P (decl))
    353 	  break;
    354 	gcc_fallthrough ();
    355       case VAR_DECL:
    356       case FIELD_DECL:
    357       case TYPE_DECL:
    358       case CONCEPT_DECL:
    359       case TEMPLATE_DECL:
    360 	return DECL_TEMPLATE_INFO (decl);
    361 
    362       default:
    363 	break;
    364       }
    365   return NULL_TREE;
    366 }
    367 
    368 /* Return the template info node corresponding to T, whatever T is.  */
    369 
    370 tree
    371 get_template_info (const_tree t)
    372 {
    373   tree tinfo = NULL_TREE;
    374 
    375   if (!t || t == error_mark_node)
    376     return NULL;
    377 
    378   if (TREE_CODE (t) == NAMESPACE_DECL
    379       || TREE_CODE (t) == PARM_DECL)
    380     return NULL;
    381 
    382   if (DECL_P (t))
    383     tinfo = decl_template_info (t);
    384 
    385   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
    386     t = TREE_TYPE (t);
    387 
    388   if (OVERLOAD_TYPE_P (t))
    389     tinfo = TYPE_TEMPLATE_INFO (t);
    390   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
    391     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
    392 
    393   return tinfo;
    394 }
    395 
    396 /* Returns the template nesting level of the indicated class TYPE.
    397 
    398    For example, in:
    399      template <class T>
    400      struct A
    401      {
    402        template <class U>
    403        struct B {};
    404      };
    405 
    406    A<T>::B<U> has depth two, while A<T> has depth one.
    407    Both A<T>::B<int> and A<int>::B<U> have depth one, if
    408    they are instantiations, not specializations.
    409 
    410    This function is guaranteed to return 0 if passed NULL_TREE so
    411    that, for example, `template_class_depth (current_class_type)' is
    412    always safe.  */
    413 
    414 int
    415 template_class_depth (tree type)
    416 {
    417   int depth;
    418 
    419   for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
    420     {
    421       tree tinfo = get_template_info (type);
    422 
    423       if (tinfo
    424 	  && TREE_CODE (TI_TEMPLATE (tinfo)) == TEMPLATE_DECL
    425 	  && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
    426 	  && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
    427 	++depth;
    428 
    429       if (DECL_P (type))
    430 	{
    431 	  if (tree fctx = DECL_FRIEND_CONTEXT (type))
    432 	    type = fctx;
    433 	  else
    434 	    type = CP_DECL_CONTEXT (type);
    435 	}
    436       else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
    437 	type = LAMBDA_TYPE_EXTRA_SCOPE (type);
    438       else
    439 	type = CP_TYPE_CONTEXT (type);
    440     }
    441 
    442   return depth;
    443 }
    444 
    445 /* Return TRUE if NODE instantiates a template that has arguments of
    446    its own, be it directly a primary template or indirectly through a
    447    partial specializations.  */
    448 static bool
    449 instantiates_primary_template_p (tree node)
    450 {
    451   tree tinfo = get_template_info (node);
    452   if (!tinfo)
    453     return false;
    454 
    455   tree tmpl = TI_TEMPLATE (tinfo);
    456   if (PRIMARY_TEMPLATE_P (tmpl))
    457     return true;
    458 
    459   if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
    460     return false;
    461 
    462   /* So now we know we have a specialization, but it could be a full
    463      or a partial specialization.  To tell which, compare the depth of
    464      its template arguments with those of its context.  */
    465 
    466   tree ctxt = DECL_CONTEXT (tmpl);
    467   tree ctinfo = get_template_info (ctxt);
    468   if (!ctinfo)
    469     return true;
    470 
    471   return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
    472 	  > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
    473 }
    474 
    475 /* Subroutine of maybe_begin_member_template_processing.
    476    Returns true if processing DECL needs us to push template parms.  */
    477 
    478 static bool
    479 inline_needs_template_parms (tree decl, bool nsdmi)
    480 {
    481   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
    482     return false;
    483 
    484   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
    485 	  > (current_template_depth + DECL_TEMPLATE_SPECIALIZATION (decl)));
    486 }
    487 
    488 /* Subroutine of maybe_begin_member_template_processing.
    489    Push the template parms in PARMS, starting from LEVELS steps into the
    490    chain, and ending at the beginning, since template parms are listed
    491    innermost first.  */
    492 
    493 static void
    494 push_inline_template_parms_recursive (tree parmlist, int levels)
    495 {
    496   tree parms = TREE_VALUE (parmlist);
    497   int i;
    498 
    499   if (levels > 1)
    500     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
    501 
    502   ++processing_template_decl;
    503   current_template_parms
    504     = tree_cons (size_int (current_template_depth + 1),
    505 		 parms, current_template_parms);
    506   TEMPLATE_PARMS_CONSTRAINTS (current_template_parms)
    507     = TEMPLATE_PARMS_CONSTRAINTS (parmlist);
    508   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
    509 
    510   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
    511 	       NULL);
    512   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
    513     {
    514       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
    515 
    516       if (error_operand_p (parm))
    517 	continue;
    518 
    519       gcc_assert (DECL_P (parm));
    520 
    521       switch (TREE_CODE (parm))
    522 	{
    523 	case TYPE_DECL:
    524 	case TEMPLATE_DECL:
    525 	  pushdecl (parm);
    526 	  break;
    527 
    528 	case PARM_DECL:
    529 	  /* Push the CONST_DECL.  */
    530 	  pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
    531 	  break;
    532 
    533 	default:
    534 	  gcc_unreachable ();
    535 	}
    536     }
    537 }
    538 
    539 /* Restore the template parameter context for a member template, a
    540    friend template defined in a class definition, or a non-template
    541    member of template class.  */
    542 
    543 void
    544 maybe_begin_member_template_processing (tree decl)
    545 {
    546   tree parms;
    547   int levels = 0;
    548   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
    549 
    550   if (nsdmi)
    551     {
    552       tree ctx = DECL_CONTEXT (decl);
    553       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
    554 	      /* Disregard full specializations (c++/60999).  */
    555 	      && uses_template_parms (ctx)
    556 	      ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
    557     }
    558 
    559   if (inline_needs_template_parms (decl, nsdmi))
    560     {
    561       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
    562       levels = TMPL_PARMS_DEPTH (parms) - current_template_depth;
    563 
    564       if (DECL_TEMPLATE_SPECIALIZATION (decl))
    565 	{
    566 	  --levels;
    567 	  parms = TREE_CHAIN (parms);
    568 	}
    569 
    570       push_inline_template_parms_recursive (parms, levels);
    571     }
    572 
    573   /* Remember how many levels of template parameters we pushed so that
    574      we can pop them later.  */
    575   inline_parm_levels.safe_push (levels);
    576 }
    577 
    578 /* Undo the effects of maybe_begin_member_template_processing.  */
    579 
    580 void
    581 maybe_end_member_template_processing (void)
    582 {
    583   int i;
    584   int last;
    585 
    586   if (inline_parm_levels.length () == 0)
    587     return;
    588 
    589   last = inline_parm_levels.pop ();
    590   for (i = 0; i < last; ++i)
    591     {
    592       --processing_template_decl;
    593       current_template_parms = TREE_CHAIN (current_template_parms);
    594       poplevel (0, 0, 0);
    595     }
    596 }
    597 
    598 /* Return a new template argument vector which contains all of ARGS,
    599    but has as its innermost set of arguments the EXTRA_ARGS.  */
    600 
    601 tree
    602 add_to_template_args (tree args, tree extra_args)
    603 {
    604   tree new_args;
    605   int extra_depth;
    606   int i;
    607   int j;
    608 
    609   if (args == NULL_TREE || extra_args == error_mark_node)
    610     return extra_args;
    611 
    612   extra_depth = TMPL_ARGS_DEPTH (extra_args);
    613   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
    614 
    615   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
    616     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
    617 
    618   for (j = 1; j <= extra_depth; ++j, ++i)
    619     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
    620 
    621   return new_args;
    622 }
    623 
    624 /* Like add_to_template_args, but only the outermost ARGS are added to
    625    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
    626    (EXTRA_ARGS) levels are added.  This function is used to combine
    627    the template arguments from a partial instantiation with the
    628    template arguments used to attain the full instantiation from the
    629    partial instantiation.
    630 
    631    If ARGS is a TEMPLATE_DECL, use its parameters as args.  */
    632 
    633 tree
    634 add_outermost_template_args (tree args, tree extra_args)
    635 {
    636   tree new_args;
    637 
    638   if (!args)
    639     return extra_args;
    640   if (TREE_CODE (args) == TEMPLATE_DECL)
    641     {
    642       tree ti = get_template_info (DECL_TEMPLATE_RESULT (args));
    643       args = TI_ARGS (ti);
    644     }
    645 
    646   /* If there are more levels of EXTRA_ARGS than there are ARGS,
    647      something very fishy is going on.  */
    648   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
    649 
    650   /* If *all* the new arguments will be the EXTRA_ARGS, just return
    651      them.  */
    652   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
    653     return extra_args;
    654 
    655   /* For the moment, we make ARGS look like it contains fewer levels.  */
    656   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
    657 
    658   new_args = add_to_template_args (args, extra_args);
    659 
    660   /* Now, we restore ARGS to its full dimensions.  */
    661   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
    662 
    663   return new_args;
    664 }
    665 
    666 /* Return the N levels of innermost template arguments from the ARGS.  */
    667 
    668 tree
    669 get_innermost_template_args (tree args, int n)
    670 {
    671   tree new_args;
    672   int extra_levels;
    673   int i;
    674 
    675   gcc_assert (n >= 0);
    676 
    677   /* If N is 1, just return the innermost set of template arguments.  */
    678   if (n == 1)
    679     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
    680 
    681   /* If we're not removing anything, just return the arguments we were
    682      given.  */
    683   extra_levels = TMPL_ARGS_DEPTH (args) - n;
    684   gcc_assert (extra_levels >= 0);
    685   if (extra_levels == 0)
    686     return args;
    687 
    688   /* Make a new set of arguments, not containing the outer arguments.  */
    689   new_args = make_tree_vec (n);
    690   for (i = 1; i <= n; ++i)
    691     SET_TMPL_ARGS_LEVEL (new_args, i,
    692 			 TMPL_ARGS_LEVEL (args, i + extra_levels));
    693 
    694   return new_args;
    695 }
    696 
    697 /* The inverse of get_innermost_template_args: Return all but the innermost
    698    EXTRA_LEVELS levels of template arguments from the ARGS.  */
    699 
    700 static tree
    701 strip_innermost_template_args (tree args, int extra_levels)
    702 {
    703   tree new_args;
    704   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
    705   int i;
    706 
    707   gcc_assert (n >= 0);
    708 
    709   /* If N is 1, just return the outermost set of template arguments.  */
    710   if (n == 1)
    711     return TMPL_ARGS_LEVEL (args, 1);
    712 
    713   /* If we're not removing anything, just return the arguments we were
    714      given.  */
    715   gcc_assert (extra_levels >= 0);
    716   if (extra_levels == 0)
    717     return args;
    718 
    719   /* Make a new set of arguments, not containing the inner arguments.  */
    720   new_args = make_tree_vec (n);
    721   for (i = 1; i <= n; ++i)
    722     SET_TMPL_ARGS_LEVEL (new_args, i,
    723 			 TMPL_ARGS_LEVEL (args, i));
    724 
    725   return new_args;
    726 }
    727 
    728 /* We've got a template header coming up; push to a new level for storing
    729    the parms.  */
    730 
    731 void
    732 begin_template_parm_list (void)
    733 {
    734   /* We use a non-tag-transparent scope here, which causes pushtag to
    735      put tags in this scope, rather than in the enclosing class or
    736      namespace scope.  This is the right thing, since we want
    737      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
    738      global template class, push_template_decl handles putting the
    739      TEMPLATE_DECL into top-level scope.  For a nested template class,
    740      e.g.:
    741 
    742        template <class T> struct S1 {
    743 	 template <class T> struct S2 {};
    744        };
    745 
    746      pushtag contains special code to insert the TEMPLATE_DECL for S2
    747      at the right scope.  */
    748   begin_scope (sk_template_parms, NULL);
    749   ++processing_template_decl;
    750   ++processing_template_parmlist;
    751   note_template_header (0);
    752 
    753   /* Add a dummy parameter level while we process the parameter list.  */
    754   current_template_parms
    755     = tree_cons (size_int (current_template_depth + 1),
    756 		 make_tree_vec (0),
    757 		 current_template_parms);
    758 }
    759 
    760 /* This routine is called when a specialization is declared.  If it is
    761    invalid to declare a specialization here, an error is reported and
    762    false is returned, otherwise this routine will return true.  */
    763 
    764 static bool
    765 check_specialization_scope (void)
    766 {
    767   tree scope = current_scope ();
    768 
    769   /* [temp.expl.spec]
    770 
    771      An explicit specialization shall be declared in the namespace of
    772      which the template is a member, or, for member templates, in the
    773      namespace of which the enclosing class or enclosing class
    774      template is a member.  An explicit specialization of a member
    775      function, member class or static data member of a class template
    776      shall be declared in the namespace of which the class template
    777      is a member.  */
    778   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
    779     {
    780       error ("explicit specialization in non-namespace scope %qD", scope);
    781       return false;
    782     }
    783 
    784   /* [temp.expl.spec]
    785 
    786      In an explicit specialization declaration for a member of a class
    787      template or a member template that appears in namespace scope,
    788      the member template and some of its enclosing class templates may
    789      remain unspecialized, except that the declaration shall not
    790      explicitly specialize a class member template if its enclosing
    791      class templates are not explicitly specialized as well.  */
    792   if (current_template_parms)
    793     {
    794       error ("enclosing class templates are not explicitly specialized");
    795       return false;
    796     }
    797 
    798   return true;
    799 }
    800 
    801 /* We've just seen template <>.  */
    802 
    803 bool
    804 begin_specialization (void)
    805 {
    806   begin_scope (sk_template_spec, NULL);
    807   note_template_header (1);
    808   return check_specialization_scope ();
    809 }
    810 
    811 /* Called at then end of processing a declaration preceded by
    812    template<>.  */
    813 
    814 void
    815 end_specialization (void)
    816 {
    817   finish_scope ();
    818   reset_specialization ();
    819 }
    820 
    821 /* Any template <>'s that we have seen thus far are not referring to a
    822    function specialization.  */
    823 
    824 void
    825 reset_specialization (void)
    826 {
    827   processing_specialization = 0;
    828   template_header_count = 0;
    829 }
    830 
    831 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
    832    it was of the form template <>.  */
    833 
    834 static void
    835 note_template_header (int specialization)
    836 {
    837   processing_specialization = specialization;
    838   template_header_count++;
    839 }
    840 
    841 /* We're beginning an explicit instantiation.  */
    842 
    843 void
    844 begin_explicit_instantiation (void)
    845 {
    846   gcc_assert (!processing_explicit_instantiation);
    847   processing_explicit_instantiation = true;
    848 }
    849 
    850 
    851 void
    852 end_explicit_instantiation (void)
    853 {
    854   gcc_assert (processing_explicit_instantiation);
    855   processing_explicit_instantiation = false;
    856 }
    857 
    858 /* An explicit specialization or partial specialization of TMPL is being
    859    declared.  Check that the namespace in which the specialization is
    860    occurring is permissible.  Returns false iff it is invalid to
    861    specialize TMPL in the current namespace.  */
    862 
    863 static bool
    864 check_specialization_namespace (tree tmpl)
    865 {
    866   tree tpl_ns = decl_namespace_context (tmpl);
    867 
    868   /* [tmpl.expl.spec]
    869 
    870      An explicit specialization shall be declared in a namespace enclosing the
    871      specialized template. An explicit specialization whose declarator-id is
    872      not qualified shall be declared in the nearest enclosing namespace of the
    873      template, or, if the namespace is inline (7.3.1), any namespace from its
    874      enclosing namespace set.  */
    875   if (current_scope() != DECL_CONTEXT (tmpl)
    876       && !at_namespace_scope_p ())
    877     {
    878       error ("specialization of %qD must appear at namespace scope", tmpl);
    879       return false;
    880     }
    881 
    882   if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
    883     /* Same or enclosing namespace.  */
    884     return true;
    885   else
    886     {
    887       auto_diagnostic_group d;
    888       if (permerror (input_location,
    889 		     "specialization of %qD in different namespace", tmpl))
    890 	inform (DECL_SOURCE_LOCATION (tmpl),
    891 		"  from definition of %q#D", tmpl);
    892       return false;
    893     }
    894 }
    895 
    896 /* SPEC is an explicit instantiation.  Check that it is valid to
    897    perform this explicit instantiation in the current namespace.  */
    898 
    899 static void
    900 check_explicit_instantiation_namespace (tree spec)
    901 {
    902   tree ns;
    903 
    904   /* DR 275: An explicit instantiation shall appear in an enclosing
    905      namespace of its template.  */
    906   ns = decl_namespace_context (spec);
    907   if (!is_nested_namespace (current_namespace, ns))
    908     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
    909 	       "(which does not enclose namespace %qD)",
    910 	       spec, current_namespace, ns);
    911 }
    912 
    913 /* Returns true if TYPE is a new partial specialization that needs to be
    914    set up.  This may also modify TYPE to point to the correct (new or
    915    existing) constrained partial specialization.  */
    916 
    917 static bool
    918 maybe_new_partial_specialization (tree& type)
    919 {
    920   /* An implicit instantiation of an incomplete type implies
    921      the definition of a new class template.
    922 
    923 	template<typename T>
    924 	  struct S;
    925 
    926 	template<typename T>
    927 	  struct S<T*>;
    928 
    929      Here, S<T*> is an implicit instantiation of S whose type
    930      is incomplete.  */
    931   if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
    932     return true;
    933 
    934   /* It can also be the case that TYPE is a completed specialization.
    935      Continuing the previous example, suppose we also declare:
    936 
    937 	template<typename T>
    938 	  requires Integral<T>
    939 	    struct S<T*>;
    940 
    941      Here, S<T*> refers to the specialization S<T*> defined
    942      above. However, we need to differentiate definitions because
    943      we intend to define a new partial specialization. In this case,
    944      we rely on the fact that the constraints are different for
    945      this declaration than that above.
    946 
    947      Note that we also get here for injected class names and
    948      late-parsed template definitions. We must ensure that we
    949      do not create new type declarations for those cases.  */
    950   if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
    951     {
    952       tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
    953       tree args = CLASSTYPE_TI_ARGS (type);
    954 
    955       /* If there are no template parameters, this cannot be a new
    956 	 partial template specialization?  */
    957       if (!current_template_parms)
    958 	return false;
    959 
    960       /* The injected-class-name is not a new partial specialization.  */
    961       if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
    962 	return false;
    963 
    964       /* If the constraints are not the same as those of the primary
    965 	 then, we can probably create a new specialization.  */
    966       tree type_constr = current_template_constraints ();
    967 
    968       if (type == TREE_TYPE (tmpl))
    969 	{
    970 	  tree main_constr = get_constraints (tmpl);
    971 	  if (equivalent_constraints (type_constr, main_constr))
    972 	    return false;
    973 	}
    974 
    975       /* Also, if there's a pre-existing specialization with matching
    976 	 constraints, then this also isn't new.  */
    977       tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
    978       while (specs)
    979         {
    980           tree spec_tmpl = TREE_VALUE (specs);
    981           tree spec_args = TREE_PURPOSE (specs);
    982           tree spec_constr = get_constraints (spec_tmpl);
    983           if (comp_template_args (args, spec_args)
    984 	      && equivalent_constraints (type_constr, spec_constr))
    985 	    {
    986 	      type = TREE_TYPE (spec_tmpl);
    987 	      return false;
    988 	    }
    989           specs = TREE_CHAIN (specs);
    990         }
    991 
    992       /* Create a new type node (and corresponding type decl)
    993 	 for the newly declared specialization.  */
    994       tree t = make_class_type (TREE_CODE (type));
    995       CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
    996       SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
    997       TYPE_CONTEXT (t) = TYPE_CONTEXT (type);
    998 
    999       /* We only need a separate type node for storing the definition of this
   1000 	 partial specialization; uses of S<T*> are unconstrained, so all are
   1001 	 equivalent.  So keep TYPE_CANONICAL the same.  */
   1002       TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
   1003 
   1004       /* Build the corresponding type decl.  */
   1005       tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
   1006       DECL_CONTEXT (d) = TYPE_CONTEXT (t);
   1007       DECL_SOURCE_LOCATION (d) = input_location;
   1008       TREE_PUBLIC (d) = TREE_PUBLIC (DECL_TEMPLATE_RESULT (tmpl));
   1009 
   1010       set_instantiating_module (d);
   1011       DECL_MODULE_EXPORT_P (d) = DECL_MODULE_EXPORT_P (tmpl);
   1012 
   1013       type = t;
   1014       return true;
   1015     }
   1016 
   1017   return false;
   1018 }
   1019 
   1020 /* The TYPE is being declared.  If it is a template type, that means it
   1021    is a partial specialization.  Do appropriate error-checking.  */
   1022 
   1023 tree
   1024 maybe_process_partial_specialization (tree type)
   1025 {
   1026   tree context;
   1027 
   1028   if (type == error_mark_node)
   1029     return error_mark_node;
   1030 
   1031   /* A lambda that appears in specialization context is not itself a
   1032      specialization.  */
   1033   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
   1034     return type;
   1035 
   1036   /* An injected-class-name is not a specialization.  */
   1037   if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
   1038     return type;
   1039 
   1040   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
   1041     {
   1042       error ("name of class shadows template template parameter %qD",
   1043 	     TYPE_NAME (type));
   1044       return error_mark_node;
   1045     }
   1046 
   1047   context = TYPE_CONTEXT (type);
   1048 
   1049   if (TYPE_ALIAS_P (type))
   1050     {
   1051       tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
   1052 
   1053       if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
   1054 	error ("specialization of alias template %qD",
   1055 	       TI_TEMPLATE (tinfo));
   1056       else
   1057 	error ("explicit specialization of non-template %qT", type);
   1058       return error_mark_node;
   1059     }
   1060   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
   1061     {
   1062       /* This is for ordinary explicit specialization and partial
   1063 	 specialization of a template class such as:
   1064 
   1065 	   template <> class C<int>;
   1066 
   1067 	 or:
   1068 
   1069 	   template <class T> class C<T*>;
   1070 
   1071 	 Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
   1072 
   1073       if (maybe_new_partial_specialization (type))
   1074 	{
   1075 	  if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type))
   1076 	      && !at_namespace_scope_p ())
   1077 	    return error_mark_node;
   1078 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
   1079 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
   1080 	  if (processing_template_decl)
   1081 	    {
   1082 	      tree decl = push_template_decl (TYPE_MAIN_DECL (type));
   1083 	      if (decl == error_mark_node)
   1084 		return error_mark_node;
   1085 	      return TREE_TYPE (decl);
   1086 	    }
   1087 	}
   1088       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
   1089 	error ("specialization of %qT after instantiation", type);
   1090       else if (errorcount && !processing_specialization
   1091 	        && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
   1092 	       && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
   1093 	/* Trying to define a specialization either without a template<> header
   1094 	   or in an inappropriate place.  We've already given an error, so just
   1095 	   bail now so we don't actually define the specialization.  */
   1096 	return error_mark_node;
   1097     }
   1098   else if (CLASS_TYPE_P (type)
   1099 	   && !CLASSTYPE_USE_TEMPLATE (type)
   1100 	   && CLASSTYPE_TEMPLATE_INFO (type)
   1101 	   && context && CLASS_TYPE_P (context)
   1102 	   && CLASSTYPE_TEMPLATE_INFO (context))
   1103     {
   1104       /* This is for an explicit specialization of member class
   1105 	 template according to [temp.expl.spec/18]:
   1106 
   1107 	   template <> template <class U> class C<int>::D;
   1108 
   1109 	 The context `C<int>' must be an implicit instantiation.
   1110 	 Otherwise this is just a member class template declared
   1111 	 earlier like:
   1112 
   1113 	   template <> class C<int> { template <class U> class D; };
   1114 	   template <> template <class U> class C<int>::D;
   1115 
   1116 	 In the first case, `C<int>::D' is a specialization of `C<T>::D'
   1117 	 while in the second case, `C<int>::D' is a primary template
   1118 	 and `C<T>::D' may not exist.  */
   1119 
   1120       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
   1121 	  && !COMPLETE_TYPE_P (type))
   1122 	{
   1123 	  tree t;
   1124 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
   1125 
   1126 	  if (current_namespace
   1127 	      != decl_namespace_context (tmpl))
   1128 	    {
   1129 	      if (permerror (input_location,
   1130 			     "specialization of %qD in different namespace",
   1131 			     type))
   1132 		inform (DECL_SOURCE_LOCATION (tmpl),
   1133 			"from definition of %q#D", tmpl);
   1134 	    }
   1135 
   1136 	  /* Check for invalid specialization after instantiation:
   1137 
   1138 	       template <> template <> class C<int>::D<int>;
   1139 	       template <> template <class U> class C<int>::D;  */
   1140 
   1141 	  for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
   1142 	       t; t = TREE_CHAIN (t))
   1143 	    {
   1144 	      tree inst = TREE_VALUE (t);
   1145 	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
   1146 		  || !COMPLETE_OR_OPEN_TYPE_P (inst))
   1147 		{
   1148 		  /* We already have a full specialization of this partial
   1149 		     instantiation, or a full specialization has been
   1150 		     looked up but not instantiated.  Reassign it to the
   1151 		     new member specialization template.  */
   1152 		  spec_entry elt;
   1153 		  spec_entry *entry;
   1154 
   1155 		  elt.tmpl = most_general_template (tmpl);
   1156 		  elt.args = CLASSTYPE_TI_ARGS (inst);
   1157 		  elt.spec = inst;
   1158 
   1159 		  type_specializations->remove_elt (&elt);
   1160 
   1161 		  elt.tmpl = tmpl;
   1162 		  CLASSTYPE_TI_ARGS (inst)
   1163 		    = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
   1164 
   1165 		  spec_entry **slot
   1166 		    = type_specializations->find_slot (&elt, INSERT);
   1167 		  entry = ggc_alloc<spec_entry> ();
   1168 		  *entry = elt;
   1169 		  *slot = entry;
   1170 		}
   1171 	      else
   1172 		/* But if we've had an implicit instantiation, that's a
   1173 		   problem ([temp.expl.spec]/6).  */
   1174 		error ("specialization %qT after instantiation %qT",
   1175 		       type, inst);
   1176 	    }
   1177 
   1178 	  /* Mark TYPE as a specialization.  And as a result, we only
   1179 	     have one level of template argument for the innermost
   1180 	     class template.  */
   1181 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
   1182 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
   1183 	  CLASSTYPE_TI_ARGS (type)
   1184 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
   1185 	}
   1186     }
   1187   else if (processing_specialization)
   1188     {
   1189        /* Someday C++0x may allow for enum template specialization.  */
   1190       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
   1191 	  && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
   1192 	pedwarn (input_location, OPT_Wpedantic, "template specialization "
   1193 		 "of %qD not allowed by ISO C++", type);
   1194       else
   1195 	{
   1196 	  error ("explicit specialization of non-template %qT", type);
   1197 	  return error_mark_node;
   1198 	}
   1199     }
   1200 
   1201   return type;
   1202 }
   1203 
   1204 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
   1205    gone through coerce_template_parms by now.  */
   1206 
   1207 static void
   1208 verify_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 
   1227 static void
   1228 verify_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 
   1250 static tree
   1251 retrieve_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   spec_entry elt;
   1278   elt.tmpl = tmpl;
   1279   elt.args = args;
   1280   elt.spec = NULL_TREE;
   1281 
   1282   spec_hash_table *specializations;
   1283   if (DECL_CLASS_TEMPLATE_P (tmpl))
   1284     specializations = type_specializations;
   1285   else
   1286     specializations = decl_specializations;
   1287 
   1288   if (hash == 0)
   1289     hash = spec_hasher::hash (&elt);
   1290   if (spec_entry *found = specializations->find_with_hash (&elt, hash))
   1291     return found->spec;
   1292 
   1293   return NULL_TREE;
   1294 }
   1295 
   1296 /* Like retrieve_specialization, but for local declarations.  */
   1297 
   1298 tree
   1299 retrieve_local_specialization (tree tmpl)
   1300 {
   1301   if (local_specializations == NULL)
   1302     return NULL_TREE;
   1303 
   1304   tree *slot = local_specializations->get (tmpl);
   1305   return slot ? *slot : NULL_TREE;
   1306 }
   1307 
   1308 /* Returns nonzero iff DECL is a specialization of TMPL.  */
   1309 
   1310 int
   1311 is_specialization_of (tree decl, tree tmpl)
   1312 {
   1313   tree t;
   1314 
   1315   if (TREE_CODE (decl) == FUNCTION_DECL)
   1316     {
   1317       for (t = decl;
   1318 	   t != NULL_TREE;
   1319 	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
   1320 	if (t == tmpl)
   1321 	  return 1;
   1322     }
   1323   else
   1324     {
   1325       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
   1326 
   1327       for (t = TREE_TYPE (decl);
   1328 	   t != NULL_TREE;
   1329 	   t = CLASSTYPE_USE_TEMPLATE (t)
   1330 	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
   1331 	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
   1332 	  return 1;
   1333     }
   1334 
   1335   return 0;
   1336 }
   1337 
   1338 /* Returns nonzero iff DECL is a specialization of friend declaration
   1339    FRIEND_DECL according to [temp.friend].  */
   1340 
   1341 bool
   1342 is_specialization_of_friend (tree decl, tree friend_decl)
   1343 {
   1344   bool need_template = true;
   1345   int template_depth;
   1346 
   1347   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
   1348 	      || TREE_CODE (decl) == TYPE_DECL);
   1349 
   1350   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
   1351      of a template class, we want to check if DECL is a specialization
   1352      if this.  */
   1353   if (TREE_CODE (friend_decl) == FUNCTION_DECL
   1354       && DECL_CLASS_SCOPE_P (friend_decl)
   1355       && DECL_TEMPLATE_INFO (friend_decl)
   1356       && !DECL_USE_TEMPLATE (friend_decl))
   1357     {
   1358       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
   1359       friend_decl = DECL_TI_TEMPLATE (friend_decl);
   1360       need_template = false;
   1361     }
   1362   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
   1363 	   && !PRIMARY_TEMPLATE_P (friend_decl))
   1364     need_template = false;
   1365 
   1366   /* There is nothing to do if this is not a template friend.  */
   1367   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
   1368     return false;
   1369 
   1370   if (is_specialization_of (decl, friend_decl))
   1371     return true;
   1372 
   1373   /* [temp.friend/6]
   1374      A member of a class template may be declared to be a friend of a
   1375      non-template class.  In this case, the corresponding member of
   1376      every specialization of the class template is a friend of the
   1377      class granting friendship.
   1378 
   1379      For example, given a template friend declaration
   1380 
   1381        template <class T> friend void A<T>::f();
   1382 
   1383      the member function below is considered a friend
   1384 
   1385        template <> struct A<int> {
   1386 	 void f();
   1387        };
   1388 
   1389      For this type of template friend, TEMPLATE_DEPTH below will be
   1390      nonzero.  To determine if DECL is a friend of FRIEND, we first
   1391      check if the enclosing class is a specialization of another.  */
   1392 
   1393   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
   1394   if (template_depth
   1395       && DECL_CLASS_SCOPE_P (decl)
   1396       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
   1397 			       CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
   1398     {
   1399       /* Next, we check the members themselves.  In order to handle
   1400 	 a few tricky cases, such as when FRIEND_DECL's are
   1401 
   1402 	   template <class T> friend void A<T>::g(T t);
   1403 	   template <class T> template <T t> friend void A<T>::h();
   1404 
   1405 	 and DECL's are
   1406 
   1407 	   void A<int>::g(int);
   1408 	   template <int> void A<int>::h();
   1409 
   1410 	 we need to figure out ARGS, the template arguments from
   1411 	 the context of DECL.  This is required for template substitution
   1412 	 of `T' in the function parameter of `g' and template parameter
   1413 	 of `h' in the above examples.  Here ARGS corresponds to `int'.  */
   1414 
   1415       tree context = DECL_CONTEXT (decl);
   1416       tree args = NULL_TREE;
   1417       int current_depth = 0;
   1418 
   1419       while (current_depth < template_depth)
   1420 	{
   1421 	  if (CLASSTYPE_TEMPLATE_INFO (context))
   1422 	    {
   1423 	      if (current_depth == 0)
   1424 		args = TYPE_TI_ARGS (context);
   1425 	      else
   1426 		args = add_to_template_args (TYPE_TI_ARGS (context), args);
   1427 	      current_depth++;
   1428 	    }
   1429 	  context = TYPE_CONTEXT (context);
   1430 	}
   1431 
   1432       if (TREE_CODE (decl) == FUNCTION_DECL)
   1433 	{
   1434 	  bool is_template;
   1435 	  tree friend_type;
   1436 	  tree decl_type;
   1437 	  tree friend_args_type;
   1438 	  tree decl_args_type;
   1439 
   1440 	  /* Make sure that both DECL and FRIEND_DECL are templates or
   1441 	     non-templates.  */
   1442 	  is_template = DECL_TEMPLATE_INFO (decl)
   1443 			&& PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
   1444 	  if (need_template ^ is_template)
   1445 	    return false;
   1446 	  else if (is_template)
   1447 	    {
   1448 	      /* If both are templates, check template parameter list.  */
   1449 	      tree friend_parms
   1450 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
   1451 					 args, tf_none);
   1452 	      if (!comp_template_parms
   1453 		     (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
   1454 		      friend_parms))
   1455 		return false;
   1456 
   1457 	      decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
   1458 	    }
   1459 	  else
   1460 	    decl_type = TREE_TYPE (decl);
   1461 
   1462 	  friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
   1463 					      tf_none, NULL_TREE);
   1464 	  if (friend_type == error_mark_node)
   1465 	    return false;
   1466 
   1467 	  /* Check if return types match.  */
   1468 	  if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
   1469 	    return false;
   1470 
   1471 	  /* Check if function parameter types match, ignoring the
   1472 	     `this' parameter.  */
   1473 	  friend_args_type = TYPE_ARG_TYPES (friend_type);
   1474 	  decl_args_type = TYPE_ARG_TYPES (decl_type);
   1475 	  if (DECL_IOBJ_MEMBER_FUNCTION_P (friend_decl))
   1476 	    friend_args_type = TREE_CHAIN (friend_args_type);
   1477 	  if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
   1478 	    decl_args_type = TREE_CHAIN (decl_args_type);
   1479 
   1480 	  return compparms (decl_args_type, friend_args_type);
   1481 	}
   1482       else
   1483 	{
   1484 	  /* DECL is a TYPE_DECL */
   1485 	  bool is_template;
   1486 	  tree decl_type = TREE_TYPE (decl);
   1487 
   1488 	  /* Make sure that both DECL and FRIEND_DECL are templates or
   1489 	     non-templates.  */
   1490 	  is_template
   1491 	    = CLASSTYPE_TEMPLATE_INFO (decl_type)
   1492 	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
   1493 
   1494 	  if (need_template ^ is_template)
   1495 	    return false;
   1496 	  else if (is_template)
   1497 	    {
   1498 	      tree friend_parms;
   1499 	      /* If both are templates, check the name of the two
   1500 		 TEMPLATE_DECL's first because is_friend didn't.  */
   1501 	      if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
   1502 		  != DECL_NAME (friend_decl))
   1503 		return false;
   1504 
   1505 	      /* Now check template parameter list.  */
   1506 	      friend_parms
   1507 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
   1508 					 args, tf_none);
   1509 	      return comp_template_parms
   1510 		(DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
   1511 		 friend_parms);
   1512 	    }
   1513 	  else
   1514 	    return (DECL_NAME (decl)
   1515 		    == DECL_NAME (friend_decl));
   1516 	}
   1517     }
   1518   return false;
   1519 }
   1520 
   1521 /* Register the specialization SPEC as a specialization of TMPL with
   1522    the indicated ARGS.  IS_FRIEND indicates whether the specialization
   1523    is actually just a friend declaration.  ATTRLIST is the list of
   1524    attributes that the specialization is declared with or NULL when
   1525    it isn't.  Returns SPEC, or an equivalent prior declaration, if
   1526    available.
   1527 
   1528    We also store instantiations of field packs in the hash table, even
   1529    though they are not themselves templates, to make lookup easier.  */
   1530 
   1531 static tree
   1532 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
   1533 			 hashval_t hash)
   1534 {
   1535   tree fn;
   1536 
   1537   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
   1538 	      || (TREE_CODE (tmpl) == FIELD_DECL
   1539 		  && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
   1540 
   1541   spec_entry elt;
   1542   elt.tmpl = tmpl;
   1543   elt.args = args;
   1544   elt.spec = spec;
   1545 
   1546   if (hash == 0)
   1547     hash = spec_hasher::hash (&elt);
   1548 
   1549   spec_entry **slot = decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
   1550   if (*slot)
   1551     fn = (*slot)->spec;
   1552   else
   1553     fn = NULL_TREE;
   1554 
   1555   /* We can sometimes try to re-register a specialization that we've
   1556      already got.  In particular, regenerate_decl_from_template calls
   1557      duplicate_decls which will update the specialization list.  But,
   1558      we'll still get called again here anyhow.  It's more convenient
   1559      to simply allow this than to try to prevent it.  */
   1560   if (fn == spec)
   1561     return spec;
   1562   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
   1563     {
   1564       if (DECL_TEMPLATE_INSTANTIATION (fn))
   1565 	{
   1566 	  if (DECL_ODR_USED (fn)
   1567 	      || DECL_EXPLICIT_INSTANTIATION (fn))
   1568 	    {
   1569 	      error ("specialization of %qD after instantiation",
   1570 		     fn);
   1571 	      return error_mark_node;
   1572 	    }
   1573 	  else
   1574 	    {
   1575 	      tree clone;
   1576 	      /* This situation should occur only if the first
   1577 		 specialization is an implicit instantiation, the
   1578 		 second is an explicit specialization, and the
   1579 		 implicit instantiation has not yet been used.  That
   1580 		 situation can occur if we have implicitly
   1581 		 instantiated a member function and then specialized
   1582 		 it later.
   1583 
   1584 		 We can also wind up here if a friend declaration that
   1585 		 looked like an instantiation turns out to be a
   1586 		 specialization:
   1587 
   1588 		   template <class T> void foo(T);
   1589 		   class S { friend void foo<>(int) };
   1590 		   template <> void foo(int);
   1591 
   1592 		 We transform the existing DECL in place so that any
   1593 		 pointers to it become pointers to the updated
   1594 		 declaration.
   1595 
   1596 		 If there was a definition for the template, but not
   1597 		 for the specialization, we want this to look as if
   1598 		 there were no definition, and vice versa.  */
   1599 	      DECL_INITIAL (fn) = NULL_TREE;
   1600 	      duplicate_decls (spec, fn, /*hiding=*/is_friend);
   1601 
   1602 	      /* The call to duplicate_decls will have applied
   1603 		 [temp.expl.spec]:
   1604 
   1605 		   An explicit specialization of a function template
   1606 		   is inline only if it is explicitly declared to be,
   1607 		   and independently of whether its function template
   1608 		   is.
   1609 
   1610 		to the primary function; now copy the inline bits to
   1611 		the various clones.  */
   1612 	      FOR_EACH_CLONE (clone, fn)
   1613 		{
   1614 		  DECL_DECLARED_INLINE_P (clone)
   1615 		    = DECL_DECLARED_INLINE_P (fn);
   1616 		  DECL_SOURCE_LOCATION (clone)
   1617 		    = DECL_SOURCE_LOCATION (fn);
   1618 		  DECL_DELETED_FN (clone)
   1619 		    = DECL_DELETED_FN (fn);
   1620 		}
   1621 	      check_specialization_namespace (tmpl);
   1622 
   1623 	      return fn;
   1624 	    }
   1625 	}
   1626       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
   1627 	{
   1628 	  tree dd = duplicate_decls (spec, fn, /*hiding=*/is_friend);
   1629 	  if (dd == error_mark_node)
   1630 	    /* We've already complained in duplicate_decls.  */
   1631 	    return error_mark_node;
   1632 
   1633 	  if (dd == NULL_TREE && DECL_INITIAL (spec))
   1634 	    /* Dup decl failed, but this is a new definition. Set the
   1635 	       line number so any errors match this new
   1636 	       definition.  */
   1637 	    DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
   1638 
   1639 	  return fn;
   1640 	}
   1641     }
   1642   else if (fn)
   1643     return duplicate_decls (spec, fn, /*hiding=*/is_friend);
   1644 
   1645   /* A specialization must be declared in the same namespace as the
   1646      template it is specializing.  */
   1647   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
   1648       && !check_specialization_namespace (tmpl))
   1649     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
   1650 
   1651   spec_entry *entry = ggc_alloc<spec_entry> ();
   1652   gcc_assert (tmpl && args && spec);
   1653   *entry = elt;
   1654   *slot = entry;
   1655   if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
   1656        && PRIMARY_TEMPLATE_P (tmpl)
   1657        && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
   1658       || variable_template_p (tmpl))
   1659     /* If TMPL is a forward declaration of a template function, keep a list
   1660        of all specializations in case we need to reassign them to a friend
   1661        template later in tsubst_friend_function.
   1662 
   1663        Also keep a list of all variable template instantiations so that
   1664        process_partial_specialization can check whether a later partial
   1665        specialization would have used it.  */
   1666     DECL_TEMPLATE_INSTANTIATIONS (tmpl)
   1667       = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
   1668 
   1669   return spec;
   1670 }
   1671 
   1672 /* Restricts tree and type comparisons.  */
   1673 int comparing_specializations;
   1674 int comparing_dependent_aliases;
   1675 
   1676 /* Whether we are comparing template arguments during partial ordering
   1677    (and therefore want the comparison to look through dependent alias
   1678    template specializations).  */
   1679 
   1680 static int comparing_for_partial_ordering;
   1681 
   1682 /* Returns true iff two spec_entry nodes are equivalent.  */
   1683 
   1684 bool
   1685 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
   1686 {
   1687   int equal;
   1688 
   1689   ++comparing_specializations;
   1690   ++comparing_dependent_aliases;
   1691   ++processing_template_decl;
   1692   equal = (e1->tmpl == e2->tmpl
   1693 	   && comp_template_args (e1->args, e2->args));
   1694   if (equal && flag_concepts
   1695       /* tmpl could be a FIELD_DECL for a capture pack.  */
   1696       && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
   1697       && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
   1698       && uses_template_parms (e1->args))
   1699     {
   1700       /* Partial specializations of a variable template can be distinguished by
   1701 	 constraints.  */
   1702       tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
   1703       tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
   1704       equal = equivalent_constraints (c1, c2);
   1705     }
   1706   --processing_template_decl;
   1707   --comparing_dependent_aliases;
   1708   --comparing_specializations;
   1709 
   1710   return equal;
   1711 }
   1712 
   1713 /* Returns a hash for a template TMPL and template arguments ARGS.  */
   1714 
   1715 static hashval_t
   1716 hash_tmpl_and_args (tree tmpl, tree args)
   1717 {
   1718   hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
   1719   return iterative_hash_template_arg (args, val);
   1720 }
   1721 
   1722 hashval_t
   1723 spec_hasher::hash (tree tmpl, tree args)
   1724 {
   1725   ++comparing_specializations;
   1726   hashval_t val = hash_tmpl_and_args (tmpl, args);
   1727   --comparing_specializations;
   1728   return val;
   1729 }
   1730 
   1731 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
   1732    ignoring SPEC.  */
   1733 
   1734 hashval_t
   1735 spec_hasher::hash (spec_entry *e)
   1736 {
   1737   return spec_hasher::hash (e->tmpl, e->args);
   1738 }
   1739 
   1740 /* Recursively calculate a hash value for a template argument ARG, for use
   1741    in the hash tables of template specializations.   We must be
   1742    careful to (at least) skip the same entities template_args_equal
   1743    does.  */
   1744 
   1745 hashval_t
   1746 iterative_hash_template_arg (tree arg, hashval_t val)
   1747 {
   1748   if (arg == NULL_TREE)
   1749     return iterative_hash_object (arg, val);
   1750 
   1751   if (!TYPE_P (arg))
   1752     /* Strip nop-like things, but not the same as STRIP_NOPS.  */
   1753     while (CONVERT_EXPR_P (arg)
   1754 	   || TREE_CODE (arg) == NON_LVALUE_EXPR
   1755 	   || class_nttp_const_wrapper_p (arg))
   1756       arg = TREE_OPERAND (arg, 0);
   1757 
   1758   enum tree_code code = TREE_CODE (arg);
   1759 
   1760   val = iterative_hash_object (code, val);
   1761 
   1762   switch (code)
   1763     {
   1764     case ARGUMENT_PACK_SELECT:
   1765       /* Getting here with an ARGUMENT_PACK_SELECT means we're probably
   1766 	 preserving it in a hash table, which is bad because it will change
   1767 	 meaning when gen_elem_of_pack_expansion_instantiation changes the
   1768 	 ARGUMENT_PACK_SELECT_INDEX.  */
   1769       gcc_unreachable ();
   1770 
   1771     case ERROR_MARK:
   1772       return val;
   1773 
   1774     case IDENTIFIER_NODE:
   1775       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
   1776 
   1777     case TREE_VEC:
   1778       for (tree elt : tree_vec_range (arg))
   1779 	val = iterative_hash_template_arg (elt, val);
   1780       return val;
   1781 
   1782     case TYPE_PACK_EXPANSION:
   1783     case EXPR_PACK_EXPANSION:
   1784       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
   1785       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
   1786 
   1787     case TYPE_ARGUMENT_PACK:
   1788     case NONTYPE_ARGUMENT_PACK:
   1789       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
   1790 
   1791     case TREE_LIST:
   1792       for (; arg; arg = TREE_CHAIN (arg))
   1793 	val = iterative_hash_template_arg (TREE_VALUE (arg), val);
   1794       return val;
   1795 
   1796     case OVERLOAD:
   1797       for (lkp_iterator iter (arg); iter; ++iter)
   1798 	val = iterative_hash_template_arg (*iter, val);
   1799       return val;
   1800 
   1801     case CONSTRUCTOR:
   1802       {
   1803 	iterative_hash_template_arg (TREE_TYPE (arg), val);
   1804 	for (auto &e: CONSTRUCTOR_ELTS (arg))
   1805 	  {
   1806 	    val = iterative_hash_template_arg (e.index, val);
   1807 	    val = iterative_hash_template_arg (e.value, val);
   1808 	  }
   1809 	return val;
   1810       }
   1811 
   1812     case PARM_DECL:
   1813       if (!DECL_ARTIFICIAL (arg))
   1814 	{
   1815 	  val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
   1816 	  val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
   1817 	}
   1818       return iterative_hash_template_arg (TREE_TYPE (arg), val);
   1819 
   1820     case TEMPLATE_DECL:
   1821       if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
   1822 	return iterative_hash_template_arg (TREE_TYPE (arg), val);
   1823       break;
   1824 
   1825     case TARGET_EXPR:
   1826       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
   1827 
   1828     case PTRMEM_CST:
   1829       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
   1830       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
   1831 
   1832     case TEMPLATE_PARM_INDEX:
   1833       val = iterative_hash_template_arg
   1834 	(TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
   1835       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
   1836       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
   1837 
   1838     case TRAIT_EXPR:
   1839       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
   1840       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
   1841       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
   1842 
   1843     case BASELINK:
   1844       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
   1845 					 val);
   1846       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
   1847 					  val);
   1848 
   1849     case MODOP_EXPR:
   1850       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
   1851       code = TREE_CODE (TREE_OPERAND (arg, 1));
   1852       val = iterative_hash_object (code, val);
   1853       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
   1854 
   1855     case LAMBDA_EXPR:
   1856       /* [temp.over.link] Two lambda-expressions are never considered
   1857 	 equivalent.
   1858 
   1859          So just hash the closure type.  */
   1860       return iterative_hash_template_arg (TREE_TYPE (arg), val);
   1861 
   1862     case CAST_EXPR:
   1863     case IMPLICIT_CONV_EXPR:
   1864     case STATIC_CAST_EXPR:
   1865     case REINTERPRET_CAST_EXPR:
   1866     case CONST_CAST_EXPR:
   1867     case DYNAMIC_CAST_EXPR:
   1868     case NEW_EXPR:
   1869       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
   1870       /* Now hash operands as usual.  */
   1871       break;
   1872 
   1873     case CALL_EXPR:
   1874       {
   1875 	tree fn = CALL_EXPR_FN (arg);
   1876 	if (tree name = call_expr_dependent_name (arg))
   1877 	  {
   1878 	    if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
   1879 	      val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
   1880 	    fn = name;
   1881 	  }
   1882 	val = iterative_hash_template_arg (fn, val);
   1883 	call_expr_arg_iterator ai;
   1884 	for (tree x = first_call_expr_arg (arg, &ai); x;
   1885 	     x = next_call_expr_arg (&ai))
   1886 	  val = iterative_hash_template_arg (x, val);
   1887 	return val;
   1888       }
   1889 
   1890     default:
   1891       break;
   1892     }
   1893 
   1894   char tclass = TREE_CODE_CLASS (code);
   1895   switch (tclass)
   1896     {
   1897     case tcc_type:
   1898       if (tree ats = alias_template_specialization_p (arg, nt_transparent))
   1899 	{
   1900 	  // We want an alias specialization that survived strip_typedefs
   1901 	  // to hash differently from its TYPE_CANONICAL, to avoid hash
   1902 	  // collisions that compare as different in template_args_equal.
   1903 	  // These could be dependent specializations that strip_typedefs
   1904 	  // left alone, or untouched specializations because
   1905 	  // coerce_template_parms returns the unconverted template
   1906 	  // arguments if it sees incomplete argument packs.
   1907 	  tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
   1908 	  return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
   1909 	}
   1910 
   1911       switch (code)
   1912 	{
   1913 	case  DECLTYPE_TYPE:
   1914 	  val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
   1915 	  break;
   1916 
   1917 	case TYPENAME_TYPE:
   1918 	  if (comparing_specializations)
   1919 	    {
   1920 	      /* Hash the components that are relevant to TYPENAME_TYPE
   1921 		 equivalence as determined by structural_comptypes.  We
   1922 		 can only coherently do this when comparing_specializations
   1923 		 is set, because otherwise structural_comptypes tries
   1924 		 resolving TYPENAME_TYPE via the current instantiation.  */
   1925 	      tree context = TYPE_MAIN_VARIANT (TYPE_CONTEXT (arg));
   1926 	      tree fullname = TYPENAME_TYPE_FULLNAME (arg);
   1927 	      val = iterative_hash_template_arg (context, val);
   1928 	      val = iterative_hash_template_arg (fullname, val);
   1929 	    }
   1930 	  break;
   1931 
   1932 	default:
   1933 	  if (tree canonical = TYPE_CANONICAL (arg))
   1934 	    val = iterative_hash_object (TYPE_HASH (canonical), val);
   1935 	  else if (tree ti = TYPE_TEMPLATE_INFO (arg))
   1936 	    {
   1937 	      val = iterative_hash_template_arg (TI_TEMPLATE (ti), val);
   1938 	      val = iterative_hash_template_arg (TI_ARGS (ti), val);
   1939 	    }
   1940 	  break;
   1941 	}
   1942 
   1943       return val;
   1944 
   1945     case tcc_declaration:
   1946     case tcc_constant:
   1947       return iterative_hash_expr (arg, val);
   1948 
   1949     default:
   1950       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
   1951       for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
   1952 	val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
   1953       return val;
   1954     }
   1955 }
   1956 
   1957 /* Unregister the specialization SPEC as a specialization of TMPL.
   1958    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
   1959    if the SPEC was listed as a specialization of TMPL.
   1960 
   1961    Note that SPEC has been ggc_freed, so we can't look inside it.  */
   1962 
   1963 bool
   1964 reregister_specialization (tree spec, tree tinfo, tree new_spec)
   1965 {
   1966   spec_entry *entry;
   1967   spec_entry elt;
   1968 
   1969   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
   1970   elt.args = TI_ARGS (tinfo);
   1971   elt.spec = NULL_TREE;
   1972 
   1973   entry = decl_specializations->find (&elt);
   1974   if (entry != NULL)
   1975     {
   1976       gcc_assert (entry->spec == spec || entry->spec == new_spec);
   1977       gcc_assert (new_spec != NULL_TREE);
   1978       entry->spec = new_spec;
   1979       return 1;
   1980     }
   1981 
   1982   return 0;
   1983 }
   1984 
   1985 /* Like register_specialization, but for local declarations.  We are
   1986    registering SPEC, an instantiation of TMPL.  */
   1987 
   1988 void
   1989 register_local_specialization (tree spec, tree tmpl)
   1990 {
   1991   gcc_assert (tmpl != spec);
   1992   local_specializations->put (tmpl, spec);
   1993 }
   1994 
   1995 /* Registers T as a specialization of itself.  This is used to preserve
   1996    the references to already-parsed parameters when instantiating
   1997    postconditions.  */
   1998 
   1999 void
   2000 register_local_identity (tree t)
   2001 {
   2002   local_specializations->put (t, t);
   2003 }
   2004 
   2005 /* TYPE is a class type.  Returns true if TYPE is an explicitly
   2006    specialized class.  */
   2007 
   2008 bool
   2009 explicit_class_specialization_p (tree type)
   2010 {
   2011   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
   2012     return false;
   2013   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
   2014 }
   2015 
   2016 /* Print the list of functions at FNS, going through all the overloads
   2017    for each element of the list.  Alternatively, FNS cannot be a
   2018    TREE_LIST, in which case it will be printed together with all the
   2019    overloads.
   2020 
   2021    MORE and *STR should respectively be FALSE and NULL when the function
   2022    is called from the outside.  They are used internally on recursive
   2023    calls.  print_candidates manages the two parameters and leaves NULL
   2024    in *STR when it ends.  */
   2025 
   2026 static void
   2027 print_candidates_1 (tree fns, char **str, bool more = false)
   2028 {
   2029   if (TREE_CODE (fns) == TREE_LIST)
   2030     for (; fns; fns = TREE_CHAIN (fns))
   2031       print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
   2032   else
   2033     for (lkp_iterator iter (fns); iter;)
   2034       {
   2035 	tree cand = *iter;
   2036 	++iter;
   2037 
   2038 	const char *pfx = *str;
   2039 	if (!pfx)
   2040 	  {
   2041 	    if (more || iter)
   2042 	      pfx = _("candidates are:");
   2043 	    else
   2044 	      pfx = _("candidate is:");
   2045 	    *str = get_spaces (pfx);
   2046 	  }
   2047 	inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
   2048       }
   2049 }
   2050 
   2051 /* Print the list of candidate FNS in an error message.  FNS can also
   2052    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
   2053 
   2054 void
   2055 print_candidates (tree fns)
   2056 {
   2057   char *str = NULL;
   2058   print_candidates_1 (fns, &str);
   2059   free (str);
   2060 }
   2061 
   2062 /* Get a (possibly) constrained template declaration for the
   2063    purpose of ordering candidates.  */
   2064 static tree
   2065 get_template_for_ordering (tree list)
   2066 {
   2067   gcc_assert (TREE_CODE (list) == TREE_LIST);
   2068   tree f = TREE_VALUE (list);
   2069   if (tree ti = DECL_TEMPLATE_INFO (f))
   2070     return TI_TEMPLATE (ti);
   2071   return f;
   2072 }
   2073 
   2074 /* Among candidates having the same signature, return the
   2075    most constrained or NULL_TREE if there is no best candidate.
   2076    If the signatures of candidates vary (e.g., template
   2077    specialization vs. member function), then there can be no
   2078    most constrained.
   2079 
   2080    Note that we don't compare constraints on the functions
   2081    themselves, but rather those of their templates. */
   2082 static tree
   2083 most_constrained_function (tree candidates)
   2084 {
   2085   // Try to find the best candidate in a first pass.
   2086   tree champ = candidates;
   2087   for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
   2088     {
   2089       int winner = more_constrained (get_template_for_ordering (champ),
   2090                                      get_template_for_ordering (c));
   2091       if (winner == -1)
   2092         champ = c; // The candidate is more constrained
   2093       else if (winner == 0)
   2094         return NULL_TREE; // Neither is more constrained
   2095     }
   2096 
   2097   // Verify that the champ is better than previous candidates.
   2098   for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
   2099     if (!more_constrained (get_template_for_ordering (champ),
   2100                            get_template_for_ordering (c)))
   2101       return NULL_TREE;
   2102   }
   2103 
   2104   return champ;
   2105 }
   2106 
   2107 
   2108 /* Returns the template (one of the functions given by TEMPLATE_ID)
   2109    which can be specialized to match the indicated DECL with the
   2110    explicit template args given in TEMPLATE_ID.  The DECL may be
   2111    NULL_TREE if none is available.  In that case, the functions in
   2112    TEMPLATE_ID are non-members.
   2113 
   2114    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
   2115    specialization of a member template.
   2116 
   2117    The TEMPLATE_COUNT is the number of references to qualifying
   2118    template classes that appeared in the name of the function. See
   2119    check_explicit_specialization for a more accurate description.
   2120 
   2121    TSK indicates what kind of template declaration (if any) is being
   2122    declared.  TSK_TEMPLATE indicates that the declaration given by
   2123    DECL, though a FUNCTION_DECL, has template parameters, and is
   2124    therefore a template function.
   2125 
   2126    The template args (those explicitly specified and those deduced)
   2127    are output in a newly created vector *TARGS_OUT.
   2128 
   2129    If it is impossible to determine the result, an error message is
   2130    issued.  The error_mark_node is returned to indicate failure.  */
   2131 
   2132 static tree
   2133 determine_specialization (tree template_id,
   2134 			  tree decl,
   2135 			  tree* targs_out,
   2136 			  int need_member_template,
   2137 			  int template_count,
   2138 			  tmpl_spec_kind tsk)
   2139 {
   2140   tree fns;
   2141   tree targs;
   2142   tree explicit_targs;
   2143   tree candidates = NULL_TREE;
   2144 
   2145   /* A TREE_LIST of templates of which DECL may be a specialization.
   2146      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
   2147      corresponding TREE_PURPOSE is the set of template arguments that,
   2148      when used to instantiate the template, would produce a function
   2149      with the signature of DECL.  */
   2150   tree templates = NULL_TREE;
   2151   int header_count;
   2152   cp_binding_level *b;
   2153 
   2154   *targs_out = NULL_TREE;
   2155 
   2156   if (template_id == error_mark_node || decl == error_mark_node)
   2157     return error_mark_node;
   2158 
   2159   /* We shouldn't be specializing a member template of an
   2160      unspecialized class template; we already gave an error in
   2161      check_specialization_scope, now avoid crashing.  */
   2162   if (!VAR_P (decl)
   2163       && template_count && DECL_CLASS_SCOPE_P (decl)
   2164       && template_class_depth (DECL_CONTEXT (decl)) > 0)
   2165     {
   2166       gcc_assert (errorcount);
   2167       return error_mark_node;
   2168     }
   2169 
   2170   fns = TREE_OPERAND (template_id, 0);
   2171   explicit_targs = TREE_OPERAND (template_id, 1);
   2172 
   2173   if (fns == error_mark_node)
   2174     return error_mark_node;
   2175 
   2176   /* Check for baselinks.  */
   2177   if (BASELINK_P (fns))
   2178     fns = BASELINK_FUNCTIONS (fns);
   2179 
   2180   if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
   2181     {
   2182       error_at (DECL_SOURCE_LOCATION (decl),
   2183 		"%qD is not a function template", fns);
   2184       return error_mark_node;
   2185     }
   2186   else if (VAR_P (decl) && !variable_template_p (fns))
   2187     {
   2188       error ("%qD is not a variable template", fns);
   2189       return error_mark_node;
   2190     }
   2191 
   2192   /* Count the number of template headers specified for this
   2193      specialization.  */
   2194   header_count = 0;
   2195   for (b = current_binding_level;
   2196        b->kind == sk_template_parms;
   2197        b = b->level_chain)
   2198     ++header_count;
   2199 
   2200   tree orig_fns = fns;
   2201   bool header_mismatch = false;
   2202 
   2203   if (variable_template_p (fns))
   2204     {
   2205       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
   2206       targs = coerce_template_parms (parms, explicit_targs, fns,
   2207 				     tf_warning_or_error);
   2208       if (targs != error_mark_node
   2209 	  && constraints_satisfied_p (fns, targs))
   2210         templates = tree_cons (targs, fns, templates);
   2211     }
   2212   else for (lkp_iterator iter (fns); iter; ++iter)
   2213     {
   2214       tree fn = *iter;
   2215 
   2216       if (TREE_CODE (fn) == TEMPLATE_DECL)
   2217 	{
   2218 	  tree decl_arg_types;
   2219 	  tree fn_arg_types;
   2220 
   2221 	  /* In case of explicit specialization, we need to check if
   2222 	     the number of template headers appearing in the specialization
   2223 	     is correct. This is usually done in check_explicit_specialization,
   2224 	     but the check done there cannot be exhaustive when specializing
   2225 	     member functions. Consider the following code:
   2226 
   2227 	     template <> void A<int>::f(int);
   2228 	     template <> template <> void A<int>::f(int);
   2229 
   2230 	     Assuming that A<int> is not itself an explicit specialization
   2231 	     already, the first line specializes "f" which is a non-template
   2232 	     member function, whilst the second line specializes "f" which
   2233 	     is a template member function. So both lines are syntactically
   2234 	     correct, and check_explicit_specialization does not reject
   2235 	     them.
   2236 
   2237 	     Here, we can do better, as we are matching the specialization
   2238 	     against the declarations. We count the number of template
   2239 	     headers, and we check if they match TEMPLATE_COUNT + 1
   2240 	     (TEMPLATE_COUNT is the number of qualifying template classes,
   2241 	     plus there must be another header for the member template
   2242 	     itself).
   2243 
   2244 	     Notice that if header_count is zero, this is not a
   2245 	     specialization but rather a template instantiation, so there
   2246 	     is no check we can perform here.  */
   2247 	  if (header_count && header_count != template_count + 1)
   2248 	    {
   2249 	      header_mismatch = true;
   2250 	      continue;
   2251 	    }
   2252 
   2253 	  /* Check that the number of template arguments at the
   2254 	     innermost level for DECL is the same as for FN.  */
   2255 	  if (current_binding_level->kind == sk_template_parms
   2256 	      && !current_binding_level->explicit_spec_p
   2257 	      && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
   2258 		  != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
   2259 				      (current_template_parms))))
   2260 	    continue;
   2261 
   2262 	  /* DECL might be a specialization of FN.  */
   2263 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
   2264 	  fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
   2265 
   2266 	  /* For a non-static member function, we need to make sure
   2267 	     that the const qualification is the same.  Since
   2268 	     get_bindings does not try to merge the "this" parameter,
   2269 	     we must do the comparison explicitly.  */
   2270 	  if (DECL_IOBJ_MEMBER_FUNCTION_P (fn))
   2271 	    {
   2272 	      if (!same_type_p (TREE_VALUE (fn_arg_types),
   2273 				TREE_VALUE (decl_arg_types)))
   2274 		continue;
   2275 
   2276 	      /* And the ref-qualification.  */
   2277 	      if (type_memfn_rqual (TREE_TYPE (decl))
   2278 		  != type_memfn_rqual (TREE_TYPE (fn)))
   2279 		continue;
   2280 	    }
   2281 
   2282 	  /* Skip the "this" parameter and, for constructors of
   2283 	     classes with virtual bases, the VTT parameter.  A
   2284 	     full specialization of a constructor will have a VTT
   2285 	     parameter, but a template never will.  */
   2286 	  decl_arg_types
   2287 	    = skip_artificial_parms_for (decl, decl_arg_types);
   2288 	  fn_arg_types
   2289 	    = skip_artificial_parms_for (fn, fn_arg_types);
   2290 
   2291 	  /* Function templates cannot be specializations; there are
   2292 	     no partial specializations of functions.  Therefore, if
   2293 	     the type of DECL does not match FN, there is no
   2294 	     match.
   2295 
   2296              Note that it should never be the case that we have both
   2297              candidates added here, and for regular member functions
   2298              below. */
   2299 	  if (tsk == tsk_template)
   2300 	    {
   2301 	      if (!comp_template_parms (DECL_TEMPLATE_PARMS (fn),
   2302 					current_template_parms))
   2303 		continue;
   2304 	      if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
   2305 				TREE_TYPE (TREE_TYPE (fn))))
   2306 		continue;
   2307 	      if (!compparms (fn_arg_types, decl_arg_types))
   2308 		continue;
   2309 
   2310 	      tree freq = get_constraints (fn);
   2311 	      tree dreq = get_constraints (decl);
   2312 	      if (!freq != !dreq)
   2313 		continue;
   2314 	      if (freq)
   2315 		{
   2316 		  /* C++20 CA104: Substitute directly into the
   2317 		     constraint-expression.  */
   2318 		  tree fargs = DECL_TI_ARGS (fn);
   2319 		  tsubst_flags_t complain = tf_none;
   2320 		  freq = tsubst_constraint_info (freq, fargs, complain, fn);
   2321 		  if (!cp_tree_equal (freq, dreq))
   2322 		    continue;
   2323 		}
   2324 
   2325 	      candidates = tree_cons (NULL_TREE, fn, candidates);
   2326 	      continue;
   2327 	    }
   2328 
   2329 	  /* See whether this function might be a specialization of this
   2330 	     template.  Suppress access control because we might be trying
   2331 	     to make this specialization a friend, and we have already done
   2332 	     access control for the declaration of the specialization.  */
   2333 	  push_deferring_access_checks (dk_no_check);
   2334 	  targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
   2335 	  pop_deferring_access_checks ();
   2336 
   2337 	  if (!targs)
   2338 	    /* We cannot deduce template arguments that when used to
   2339 	       specialize TMPL will produce DECL.  */
   2340 	    continue;
   2341 
   2342 	  if (uses_template_parms (targs))
   2343 	    /* We deduced something involving 'auto', which isn't a valid
   2344 	       template argument.  */
   2345 	    continue;
   2346 
   2347 	  /* Save this template, and the arguments deduced.  */
   2348 	  templates = tree_cons (targs, fn, templates);
   2349 	}
   2350       else if (need_member_template)
   2351 	/* FN is an ordinary member function, and we need a
   2352 	   specialization of a member template.  */
   2353 	;
   2354       else if (TREE_CODE (fn) != FUNCTION_DECL)
   2355 	/* We can get IDENTIFIER_NODEs here in certain erroneous
   2356 	   cases.  */
   2357 	;
   2358       else if (!DECL_FUNCTION_MEMBER_P (fn))
   2359 	/* This is just an ordinary non-member function.  Nothing can
   2360 	   be a specialization of that.  */
   2361 	;
   2362       else if (DECL_ARTIFICIAL (fn))
   2363 	/* Cannot specialize functions that are created implicitly.  */
   2364 	;
   2365       else
   2366 	{
   2367 	  tree decl_arg_types;
   2368 
   2369 	  /* This is an ordinary member function.  However, since
   2370 	     we're here, we can assume its enclosing class is a
   2371 	     template class.  For example,
   2372 
   2373 	       template <typename T> struct S { void f(); };
   2374 	       template <> void S<int>::f() {}
   2375 
   2376 	     Here, S<int>::f is a non-template, but S<int> is a
   2377 	     template class.  If FN has the same type as DECL, we
   2378 	     might be in business.  */
   2379 
   2380 	  if (!DECL_TEMPLATE_INFO (fn))
   2381 	    /* Its enclosing class is an explicit specialization
   2382 	       of a template class.  This is not a candidate.  */
   2383 	    continue;
   2384 
   2385 	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
   2386 			    TREE_TYPE (TREE_TYPE (fn))))
   2387 	    /* The return types differ.  */
   2388 	    continue;
   2389 
   2390 	  /* Adjust the type of DECL in case FN is a static member.  */
   2391 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
   2392 	  if (DECL_STATIC_FUNCTION_P (fn)
   2393 	      && DECL_IOBJ_MEMBER_FUNCTION_P (decl))
   2394 	    decl_arg_types = TREE_CHAIN (decl_arg_types);
   2395 
   2396 	  if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
   2397 			 decl_arg_types))
   2398             continue;
   2399 
   2400 	  if (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
   2401 	      && (type_memfn_rqual (TREE_TYPE (decl))
   2402 		  != type_memfn_rqual (TREE_TYPE (fn))))
   2403 	    continue;
   2404 
   2405           // If the deduced arguments do not satisfy the constraints,
   2406           // this is not a candidate.
   2407           if (flag_concepts && !constraints_satisfied_p (fn))
   2408             continue;
   2409 
   2410           // Add the candidate.
   2411           candidates = tree_cons (NULL_TREE, fn, candidates);
   2412 	}
   2413     }
   2414 
   2415   if (templates && TREE_CHAIN (templates))
   2416     {
   2417       /* We have:
   2418 
   2419 	   [temp.expl.spec]
   2420 
   2421 	   It is possible for a specialization with a given function
   2422 	   signature to be instantiated from more than one function
   2423 	   template.  In such cases, explicit specification of the
   2424 	   template arguments must be used to uniquely identify the
   2425 	   function template specialization being specialized.
   2426 
   2427 	 Note that here, there's no suggestion that we're supposed to
   2428 	 determine which of the candidate templates is most
   2429 	 specialized.  However, we, also have:
   2430 
   2431 	   [temp.func.order]
   2432 
   2433 	   Partial ordering of overloaded function template
   2434 	   declarations is used in the following contexts to select
   2435 	   the function template to which a function template
   2436 	   specialization refers:
   2437 
   2438 	   -- when an explicit specialization refers to a function
   2439 	      template.
   2440 
   2441 	 So, we do use the partial ordering rules, at least for now.
   2442 	 This extension can only serve to make invalid programs valid,
   2443 	 so it's safe.  And, there is strong anecdotal evidence that
   2444 	 the committee intended the partial ordering rules to apply;
   2445 	 the EDG front end has that behavior, and John Spicer claims
   2446 	 that the committee simply forgot to delete the wording in
   2447 	 [temp.expl.spec].  */
   2448       tree tmpl = most_specialized_instantiation (templates);
   2449       if (tmpl != error_mark_node)
   2450 	{
   2451 	  templates = tmpl;
   2452 	  TREE_CHAIN (templates) = NULL_TREE;
   2453 	}
   2454     }
   2455 
   2456   // Concepts allows multiple declarations of member functions
   2457   // with the same signature. Like above, we need to rely on
   2458   // on the partial ordering of those candidates to determine which
   2459   // is the best.
   2460   if (flag_concepts && candidates && TREE_CHAIN (candidates))
   2461     {
   2462       if (tree cand = most_constrained_function (candidates))
   2463         {
   2464           candidates = cand;
   2465           TREE_CHAIN (cand) = NULL_TREE;
   2466         }
   2467     }
   2468 
   2469   if (templates == NULL_TREE && candidates == NULL_TREE)
   2470     {
   2471       error ("template-id %qD for %q+D does not match any template "
   2472 	     "declaration", template_id, decl);
   2473       if (header_mismatch)
   2474 	inform (DECL_SOURCE_LOCATION (decl),
   2475 		"saw %d %<template<>%>, need %d for "
   2476 		"specializing a member function template",
   2477 		header_count, template_count + 1);
   2478       print_candidates (orig_fns);
   2479       return error_mark_node;
   2480     }
   2481   else if ((templates && TREE_CHAIN (templates))
   2482 	   || (candidates && TREE_CHAIN (candidates))
   2483 	   || (templates && candidates))
   2484     {
   2485       error ("ambiguous template specialization %qD for %q+D",
   2486 	     template_id, decl);
   2487       candidates = chainon (candidates, templates);
   2488       print_candidates (candidates);
   2489       return error_mark_node;
   2490     }
   2491 
   2492   /* We have one, and exactly one, match.  */
   2493   if (candidates)
   2494     {
   2495       tree fn = TREE_VALUE (candidates);
   2496       *targs_out = copy_node (DECL_TI_ARGS (fn));
   2497 
   2498       /* Propagate the candidate's constraints to the declaration.  */
   2499       if (tsk != tsk_template)
   2500 	set_constraints (decl, get_constraints (fn));
   2501 
   2502       /* DECL is a re-declaration or partial instantiation of a template
   2503 	 function.  */
   2504       if (TREE_CODE (fn) == TEMPLATE_DECL)
   2505 	return fn;
   2506       /* It was a specialization of an ordinary member function in a
   2507 	 template class.  */
   2508       return DECL_TI_TEMPLATE (fn);
   2509     }
   2510 
   2511   /* It was a specialization of a template.  */
   2512   tree tmpl = TREE_VALUE (templates);
   2513   *targs_out = add_outermost_template_args (tmpl, TREE_PURPOSE (templates));
   2514 
   2515   /* Propagate the template's constraints to the declaration.  */
   2516   if (tsk != tsk_template)
   2517     set_constraints (decl, get_constraints (tmpl));
   2518 
   2519   return tmpl;
   2520 }
   2521 
   2522 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
   2523    but with the default argument values filled in from those in the
   2524    TMPL_TYPES.  */
   2525 
   2526 static tree
   2527 copy_default_args_to_explicit_spec_1 (tree spec_types,
   2528 				      tree tmpl_types)
   2529 {
   2530   tree new_spec_types;
   2531 
   2532   if (!spec_types)
   2533     return NULL_TREE;
   2534 
   2535   if (spec_types == void_list_node)
   2536     return void_list_node;
   2537 
   2538   /* Substitute into the rest of the list.  */
   2539   new_spec_types =
   2540     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
   2541 					  TREE_CHAIN (tmpl_types));
   2542 
   2543   /* Add the default argument for this parameter.  */
   2544   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
   2545 			 TREE_VALUE (spec_types),
   2546 			 new_spec_types);
   2547 }
   2548 
   2549 /* DECL is an explicit specialization.  Replicate default arguments
   2550    from the template it specializes.  (That way, code like:
   2551 
   2552      template <class T> void f(T = 3);
   2553      template <> void f(double);
   2554      void g () { f (); }
   2555 
   2556    works, as required.)  An alternative approach would be to look up
   2557    the correct default arguments at the call-site, but this approach
   2558    is consistent with how implicit instantiations are handled.  */
   2559 
   2560 static void
   2561 copy_default_args_to_explicit_spec (tree decl)
   2562 {
   2563   tree tmpl;
   2564   tree spec_types;
   2565   tree tmpl_types;
   2566   tree new_spec_types;
   2567   tree old_type;
   2568   tree new_type;
   2569   tree t;
   2570   tree object_type = NULL_TREE;
   2571   tree in_charge = NULL_TREE;
   2572   tree vtt = NULL_TREE;
   2573 
   2574   /* See if there's anything we need to do.  */
   2575   tmpl = DECL_TI_TEMPLATE (decl);
   2576   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
   2577   for (t = tmpl_types; t; t = TREE_CHAIN (t))
   2578     if (TREE_PURPOSE (t))
   2579       break;
   2580   if (!t)
   2581     return;
   2582 
   2583   old_type = TREE_TYPE (decl);
   2584   spec_types = TYPE_ARG_TYPES (old_type);
   2585 
   2586   if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
   2587     {
   2588       /* Remove the this pointer, but remember the object's type for
   2589 	 CV quals.  */
   2590       object_type = TREE_TYPE (TREE_VALUE (spec_types));
   2591       spec_types = TREE_CHAIN (spec_types);
   2592       tmpl_types = TREE_CHAIN (tmpl_types);
   2593 
   2594       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
   2595 	{
   2596 	  /* DECL may contain more parameters than TMPL due to the extra
   2597 	     in-charge parameter in constructors and destructors.  */
   2598 	  in_charge = spec_types;
   2599 	  spec_types = TREE_CHAIN (spec_types);
   2600 	}
   2601       if (DECL_HAS_VTT_PARM_P (decl))
   2602 	{
   2603 	  vtt = spec_types;
   2604 	  spec_types = TREE_CHAIN (spec_types);
   2605 	}
   2606     }
   2607 
   2608   /* Compute the merged default arguments.  */
   2609   new_spec_types =
   2610     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
   2611 
   2612   /* Compute the new FUNCTION_TYPE.  */
   2613   if (object_type)
   2614     {
   2615       if (vtt)
   2616 	new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
   2617 					 TREE_VALUE (vtt),
   2618 					 new_spec_types);
   2619 
   2620       if (in_charge)
   2621 	/* Put the in-charge parameter back.  */
   2622 	new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
   2623 					 TREE_VALUE (in_charge),
   2624 					 new_spec_types);
   2625 
   2626       new_type = build_method_type_directly (object_type,
   2627 					     TREE_TYPE (old_type),
   2628 					     new_spec_types);
   2629     }
   2630   else
   2631     new_type = build_function_type (TREE_TYPE (old_type),
   2632 				    new_spec_types);
   2633   new_type = cp_build_type_attribute_variant (new_type,
   2634 					      TYPE_ATTRIBUTES (old_type));
   2635   new_type = cxx_copy_lang_qualifiers (new_type, old_type);
   2636 
   2637   TREE_TYPE (decl) = new_type;
   2638 }
   2639 
   2640 /* Return the number of template headers we expect to see for a definition
   2641    or specialization of CTYPE or one of its non-template members.  */
   2642 
   2643 int
   2644 num_template_headers_for_class (tree ctype)
   2645 {
   2646   int num_templates = 0;
   2647 
   2648   while (ctype && CLASS_TYPE_P (ctype))
   2649     {
   2650       /* You're supposed to have one `template <...>' for every
   2651 	 template class, but you don't need one for a full
   2652 	 specialization.  For example:
   2653 
   2654 	 template <class T> struct S{};
   2655 	 template <> struct S<int> { void f(); };
   2656 	 void S<int>::f () {}
   2657 
   2658 	 is correct; there shouldn't be a `template <>' for the
   2659 	 definition of `S<int>::f'.  */
   2660       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
   2661 	/* If CTYPE does not have template information of any
   2662 	   kind,  then it is not a template, nor is it nested
   2663 	   within a template.  */
   2664 	break;
   2665       if (explicit_class_specialization_p (ctype))
   2666 	break;
   2667       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
   2668 	++num_templates;
   2669 
   2670       ctype = TYPE_CONTEXT (ctype);
   2671     }
   2672 
   2673   return num_templates;
   2674 }
   2675 
   2676 /* Do a simple sanity check on the template headers that precede the
   2677    variable declaration DECL.  */
   2678 
   2679 void
   2680 check_template_variable (tree decl)
   2681 {
   2682   tree ctx = CP_DECL_CONTEXT (decl);
   2683   int wanted = num_template_headers_for_class (ctx);
   2684   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
   2685       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
   2686     {
   2687       if (cxx_dialect < cxx14)
   2688         pedwarn (DECL_SOURCE_LOCATION (decl), OPT_Wc__14_extensions,
   2689 		 "variable templates only available with "
   2690 		 "%<-std=c++14%> or %<-std=gnu++14%>");
   2691 
   2692       // Namespace-scope variable templates should have a template header.
   2693       ++wanted;
   2694     }
   2695   if (template_header_count > wanted)
   2696     {
   2697       auto_diagnostic_group d;
   2698       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
   2699 			     "too many template headers for %qD "
   2700 	                     "(should be %d)",
   2701 			     decl, wanted);
   2702       if (warned && CLASS_TYPE_P (ctx)
   2703 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
   2704 	inform (DECL_SOURCE_LOCATION (decl),
   2705 		"members of an explicitly specialized class are defined "
   2706 		"without a template header");
   2707     }
   2708 }
   2709 
   2710 /* An explicit specialization whose declarator-id or class-head-name is not
   2711    qualified shall be declared in the nearest enclosing namespace of the
   2712    template, or, if the namespace is inline (7.3.1), any namespace from its
   2713    enclosing namespace set.
   2714 
   2715    If the name declared in the explicit instantiation is an unqualified name,
   2716    the explicit instantiation shall appear in the namespace where its template
   2717    is declared or, if that namespace is inline (7.3.1), any namespace from its
   2718    enclosing namespace set.  */
   2719 
   2720 void
   2721 check_unqualified_spec_or_inst (tree t, location_t loc)
   2722 {
   2723   tree tmpl = most_general_template (t);
   2724   if (DECL_NAMESPACE_SCOPE_P (tmpl)
   2725       && !is_nested_namespace (current_namespace,
   2726 			       CP_DECL_CONTEXT (tmpl), true))
   2727     {
   2728       if (processing_specialization)
   2729 	permerror (loc, "explicit specialization of %qD outside its "
   2730 		   "namespace must use a nested-name-specifier", tmpl);
   2731       else if (processing_explicit_instantiation
   2732 	       && cxx_dialect >= cxx11)
   2733 	/* This was allowed in C++98, so only pedwarn.  */
   2734 	pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
   2735 		 "outside its namespace must use a nested-name-"
   2736 		 "specifier", tmpl);
   2737     }
   2738 }
   2739 
   2740 /* Warn for a template specialization SPEC that is missing some of a set
   2741    of function or type attributes that the template TEMPL is declared with.
   2742    ATTRLIST is a list of additional attributes that SPEC should be taken
   2743    to ultimately be declared with.  */
   2744 
   2745 static void
   2746 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
   2747 {
   2748   if (DECL_FUNCTION_TEMPLATE_P (tmpl))
   2749     tmpl = DECL_TEMPLATE_RESULT (tmpl);
   2750 
   2751   /* Avoid warning if the difference between the primary and
   2752      the specialization is not in one of the attributes below.  */
   2753   const char* const blacklist[] = {
   2754     "alloc_align", "alloc_size", "assume_aligned", "format",
   2755     "format_arg", "malloc", "nonnull", NULL
   2756   };
   2757 
   2758   /* Put together a list of the black listed attributes that the primary
   2759      template is declared with that the specialization is not, in case
   2760      it's not apparent from the most recent declaration of the primary.  */
   2761   pretty_printer str;
   2762   unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
   2763 						 blacklist, &str);
   2764 
   2765   if (!nattrs)
   2766     return;
   2767 
   2768   auto_diagnostic_group d;
   2769   if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
   2770 		  "explicit specialization %q#D may be missing attributes",
   2771 		  spec))
   2772     inform (DECL_SOURCE_LOCATION (tmpl),
   2773 	    nattrs > 1
   2774 	    ? G_("missing primary template attributes %s")
   2775 	    : G_("missing primary template attribute %s"),
   2776 	    pp_formatted_text (&str));
   2777 }
   2778 
   2779 /* Check to see if the function just declared, as indicated in
   2780    DECLARATOR, and in DECL, is a specialization of a function
   2781    template.  We may also discover that the declaration is an explicit
   2782    instantiation at this point.
   2783 
   2784    Returns DECL, or an equivalent declaration that should be used
   2785    instead if all goes well.  Issues an error message if something is
   2786    amiss.  Returns error_mark_node if the error is not easily
   2787    recoverable.
   2788 
   2789    FLAGS is a bitmask consisting of the following flags:
   2790 
   2791    2: The function has a definition.
   2792    4: The function is a friend.
   2793 
   2794    The TEMPLATE_COUNT is the number of references to qualifying
   2795    template classes that appeared in the name of the function.  For
   2796    example, in
   2797 
   2798      template <class T> struct S { void f(); };
   2799      void S<int>::f();
   2800 
   2801    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
   2802    classes are not counted in the TEMPLATE_COUNT, so that in
   2803 
   2804      template <class T> struct S {};
   2805      template <> struct S<int> { void f(); }
   2806      template <> void S<int>::f();
   2807 
   2808    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
   2809    invalid; there should be no template <>.)
   2810 
   2811    If the function is a specialization, it is marked as such via
   2812    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
   2813    is set up correctly, and it is added to the list of specializations
   2814    for that template.  */
   2815 
   2816 tree
   2817 check_explicit_specialization (tree declarator,
   2818 			       tree decl,
   2819 			       int template_count,
   2820 			       int flags,
   2821 			       tree attrlist)
   2822 {
   2823   int have_def = flags & 2;
   2824   int is_friend = flags & 4;
   2825   bool is_concept = flags & 8;
   2826   int specialization = 0;
   2827   int explicit_instantiation = 0;
   2828   int member_specialization = 0;
   2829   tree ctype = DECL_CLASS_CONTEXT (decl);
   2830   tree dname = DECL_NAME (decl);
   2831   tmpl_spec_kind tsk;
   2832 
   2833   if (is_friend)
   2834     {
   2835       if (!processing_specialization)
   2836 	tsk = tsk_none;
   2837       else
   2838 	tsk = tsk_excessive_parms;
   2839     }
   2840   else
   2841     tsk = current_tmpl_spec_kind (template_count);
   2842 
   2843   switch (tsk)
   2844     {
   2845     case tsk_none:
   2846       if (processing_specialization && !VAR_P (decl))
   2847 	{
   2848 	  specialization = 1;
   2849 	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
   2850 	}
   2851       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR
   2852 	       || (DECL_LANG_SPECIFIC (decl)
   2853 		   && DECL_IMPLICIT_INSTANTIATION (decl)))
   2854 	{
   2855 	  if (is_friend)
   2856 	    /* This could be something like:
   2857 
   2858 	       template <class T> void f(T);
   2859 	       class S { friend void f<>(int); }  */
   2860 	    specialization = 1;
   2861 	  else
   2862 	    {
   2863 	      /* This case handles bogus declarations like template <>
   2864 		 template <class T> void f<int>(); */
   2865 
   2866 	      error_at (cp_expr_loc_or_input_loc (declarator),
   2867 			"template-id %qE in declaration of primary template",
   2868 			declarator);
   2869 	      return decl;
   2870 	    }
   2871 	}
   2872       break;
   2873 
   2874     case tsk_invalid_member_spec:
   2875       /* The error has already been reported in
   2876 	 check_specialization_scope.  */
   2877       return error_mark_node;
   2878 
   2879     case tsk_invalid_expl_inst:
   2880       error ("template parameter list used in explicit instantiation");
   2881 
   2882       /* Fall through.  */
   2883 
   2884     case tsk_expl_inst:
   2885       if (have_def)
   2886 	error ("definition provided for explicit instantiation");
   2887 
   2888       explicit_instantiation = 1;
   2889       break;
   2890 
   2891     case tsk_excessive_parms:
   2892     case tsk_insufficient_parms:
   2893       if (tsk == tsk_excessive_parms)
   2894 	error ("too many template parameter lists in declaration of %qD",
   2895 	       decl);
   2896       else if (template_header_count)
   2897 	error("too few template parameter lists in declaration of %qD", decl);
   2898       else
   2899 	error("explicit specialization of %qD must be introduced by "
   2900 	      "%<template <>%>", decl);
   2901 
   2902       /* Fall through.  */
   2903     case tsk_expl_spec:
   2904       if (is_concept)
   2905         error ("explicit specialization declared %<concept%>");
   2906 
   2907       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
   2908 	/* In cases like template<> constexpr bool v = true;
   2909 	   We'll give an error in check_template_variable.  */
   2910 	break;
   2911 
   2912       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
   2913       if (ctype)
   2914 	member_specialization = 1;
   2915       else
   2916 	specialization = 1;
   2917       break;
   2918 
   2919     case tsk_template:
   2920       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
   2921 	{
   2922 	  /* This case handles bogus declarations like template <>
   2923 	     template <class T> void f<int>(); */
   2924 
   2925 	  if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
   2926 	    error_at (cp_expr_loc_or_input_loc (declarator),
   2927 		      "template-id %qE in declaration of primary template",
   2928 		      declarator);
   2929 	  else if (variable_template_p (TREE_OPERAND (declarator, 0)))
   2930 	    {
   2931 	      /* Partial specialization of variable template.  */
   2932 	      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
   2933 	      specialization = 1;
   2934 	      goto ok;
   2935 	    }
   2936 	  else if (cxx_dialect < cxx14)
   2937 	    error_at (cp_expr_loc_or_input_loc (declarator),
   2938 		      "non-type partial specialization %qE "
   2939 		      "is not allowed", declarator);
   2940 	  else
   2941 	    error_at (cp_expr_loc_or_input_loc (declarator),
   2942 		      "non-class, non-variable partial specialization %qE "
   2943 		      "is not allowed", declarator);
   2944 	  return decl;
   2945 	ok:;
   2946 	}
   2947 
   2948       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
   2949 	/* This is a specialization of a member template, without
   2950 	   specialization the containing class.  Something like:
   2951 
   2952 	     template <class T> struct S {
   2953 	       template <class U> void f (U);
   2954 	     };
   2955 	     template <> template <class U> void S<int>::f(U) {}
   2956 
   2957 	   That's a specialization -- but of the entire template.  */
   2958 	specialization = 1;
   2959       break;
   2960 
   2961     default:
   2962       gcc_unreachable ();
   2963     }
   2964 
   2965   if ((specialization || member_specialization)
   2966       /* This doesn't apply to variable templates.  */
   2967       && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
   2968     {
   2969       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
   2970       for (; t; t = TREE_CHAIN (t))
   2971 	if (TREE_PURPOSE (t))
   2972 	  {
   2973 	    permerror (input_location,
   2974 		       "default argument specified in explicit specialization");
   2975 	    break;
   2976 	  }
   2977     }
   2978 
   2979   if (specialization || member_specialization || explicit_instantiation)
   2980     {
   2981       tree tmpl = NULL_TREE;
   2982       tree targs = NULL_TREE;
   2983       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
   2984       bool found_hidden = false;
   2985 
   2986       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
   2987       if (!was_template_id)
   2988 	{
   2989 	  tree fns;
   2990 
   2991 	  gcc_assert (identifier_p (declarator));
   2992 	  if (ctype)
   2993 	    fns = dname;
   2994 	  else
   2995 	    {
   2996 	      /* If there is no class context, the explicit instantiation
   2997 		 must be at namespace scope.  */
   2998 	      gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
   2999 
   3000 	      /* Find the namespace binding, using the declaration
   3001 		 context.  */
   3002 	      fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
   3003 					   LOOK_want::NORMAL, true);
   3004 	      if (fns == error_mark_node)
   3005 		{
   3006 		  /* If lookup fails, look for a friend declaration so we can
   3007 		     give a better diagnostic.  */
   3008 		  fns = (lookup_qualified_name
   3009 			 (CP_DECL_CONTEXT (decl), dname,
   3010 			  LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND,
   3011 			  /*complain*/true));
   3012 		  found_hidden = true;
   3013 		}
   3014 
   3015 	      if (fns == error_mark_node || !is_overloaded_fn (fns))
   3016 		{
   3017 		  error ("%qD is not a template function", dname);
   3018 		  fns = error_mark_node;
   3019 		}
   3020 	    }
   3021 
   3022 	  declarator = lookup_template_function (fns, NULL_TREE);
   3023 	}
   3024 
   3025       if (declarator == error_mark_node)
   3026 	return error_mark_node;
   3027 
   3028       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
   3029 	{
   3030 	  if (!explicit_instantiation)
   3031 	    /* A specialization in class scope.  This is invalid,
   3032 	       but the error will already have been flagged by
   3033 	       check_specialization_scope.  */
   3034 	    return error_mark_node;
   3035 	  else
   3036 	    {
   3037 	      /* It's not valid to write an explicit instantiation in
   3038 		 class scope, e.g.:
   3039 
   3040 		   class C { template void f(); }
   3041 
   3042 		   This case is caught by the parser.  However, on
   3043 		   something like:
   3044 
   3045 		   template class C { void f(); };
   3046 
   3047 		   (which is invalid) we can get here.  The error will be
   3048 		   issued later.  */
   3049 	      ;
   3050 	    }
   3051 
   3052 	  return decl;
   3053 	}
   3054       else if (ctype != NULL_TREE
   3055 	       && (identifier_p (TREE_OPERAND (declarator, 0))))
   3056 	{
   3057 	  // We'll match variable templates in start_decl.
   3058 	  if (VAR_P (decl))
   3059 	    return decl;
   3060 
   3061 	  /* Find the list of functions in ctype that have the same
   3062 	     name as the declared function.  */
   3063 	  tree name = TREE_OPERAND (declarator, 0);
   3064 
   3065 	  if (constructor_name_p (name, ctype))
   3066 	    {
   3067 	      if (DECL_CONSTRUCTOR_P (decl)
   3068 		  ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
   3069 		  : !CLASSTYPE_DESTRUCTOR (ctype))
   3070 		{
   3071 		  /* From [temp.expl.spec]:
   3072 
   3073 		     If such an explicit specialization for the member
   3074 		     of a class template names an implicitly-declared
   3075 		     special member function (clause _special_), the
   3076 		     program is ill-formed.
   3077 
   3078 		     Similar language is found in [temp.explicit].  */
   3079 		  error ("specialization of implicitly-declared special member function");
   3080 		  return error_mark_node;
   3081 		}
   3082 
   3083 	      name = DECL_NAME (decl);
   3084 	    }
   3085 
   3086 	  /* For a type-conversion operator, We might be looking for
   3087 	     `operator int' which will be a specialization of
   3088 	     `operator T'.  Grab all the conversion operators, and
   3089 	     then select from them.  */
   3090 	  tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
   3091 					? conv_op_identifier : name);
   3092 
   3093 	  if (fns == NULL_TREE)
   3094 	    {
   3095 	      error ("no member function %qD declared in %qT", name, ctype);
   3096 	      return error_mark_node;
   3097 	    }
   3098 	  else
   3099 	    TREE_OPERAND (declarator, 0) = fns;
   3100 	}
   3101 
   3102       /* Figure out what exactly is being specialized at this point.
   3103 	 Note that for an explicit instantiation, even one for a
   3104 	 member function, we cannot tell a priori whether the
   3105 	 instantiation is for a member template, or just a member
   3106 	 function of a template class.  Even if a member template is
   3107 	 being instantiated, the member template arguments may be
   3108 	 elided if they can be deduced from the rest of the
   3109 	 declaration.  */
   3110       tmpl = determine_specialization (declarator, decl,
   3111 				       &targs,
   3112 				       member_specialization,
   3113 				       template_count,
   3114 				       tsk);
   3115 
   3116       if (!tmpl || tmpl == error_mark_node)
   3117 	/* We couldn't figure out what this declaration was
   3118 	   specializing.  */
   3119 	return error_mark_node;
   3120       else
   3121 	{
   3122 	  if (found_hidden && TREE_CODE (decl) == FUNCTION_DECL)
   3123 	    {
   3124 	      auto_diagnostic_group d;
   3125 	      if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
   3126 			   "friend declaration %qD is not visible to "
   3127 			   "explicit specialization", tmpl))
   3128 		inform (DECL_SOURCE_LOCATION (tmpl),
   3129 			"friend declaration here");
   3130 	    }
   3131 
   3132 	  if (!ctype && !is_friend
   3133 	      && CP_DECL_CONTEXT (decl) == current_namespace)
   3134 	    check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
   3135 
   3136 	  tree gen_tmpl = most_general_template (tmpl);
   3137 
   3138 	  if (explicit_instantiation)
   3139 	    {
   3140 	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
   3141 		 is done by do_decl_instantiation later.  */
   3142 
   3143 	      int arg_depth = TMPL_ARGS_DEPTH (targs);
   3144 	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
   3145 
   3146 	      if (arg_depth > parm_depth)
   3147 		{
   3148 		  /* If TMPL is not the most general template (for
   3149 		     example, if TMPL is a friend template that is
   3150 		     injected into namespace scope), then there will
   3151 		     be too many levels of TARGS.  Remove some of them
   3152 		     here.  */
   3153 		  int i;
   3154 		  tree new_targs;
   3155 
   3156 		  new_targs = make_tree_vec (parm_depth);
   3157 		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
   3158 		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
   3159 		      = TREE_VEC_ELT (targs, i);
   3160 		  targs = new_targs;
   3161 		}
   3162 
   3163 	      return instantiate_template (tmpl, targs, tf_error);
   3164 	    }
   3165 
   3166 	  /* If we thought that the DECL was a member function, but it
   3167 	     turns out to be specializing a static member function,
   3168 	     make DECL a static member function as well.  */
   3169 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl)
   3170 	      && DECL_STATIC_FUNCTION_P (tmpl)
   3171 	      && DECL_IOBJ_MEMBER_FUNCTION_P (decl))
   3172 	    revert_static_member_fn (decl);
   3173 
   3174 	  /* If this is a specialization of a member template of a
   3175 	     template class, we want to return the TEMPLATE_DECL, not
   3176 	     the specialization of it.  */
   3177 	  if (tsk == tsk_template && !was_template_id)
   3178 	    {
   3179 	      tree result = DECL_TEMPLATE_RESULT (tmpl);
   3180 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
   3181 	      DECL_INITIAL (result) = NULL_TREE;
   3182 	      if (have_def)
   3183 		{
   3184 		  tree parm;
   3185 		  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
   3186 		  DECL_SOURCE_LOCATION (result)
   3187 		    = DECL_SOURCE_LOCATION (decl);
   3188 		  /* We want to use the argument list specified in the
   3189 		     definition, not in the original declaration.  */
   3190 		  DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
   3191 		  for (parm = DECL_ARGUMENTS (result); parm;
   3192 		       parm = DECL_CHAIN (parm))
   3193 		    DECL_CONTEXT (parm) = result;
   3194 		}
   3195 	      decl = register_specialization (tmpl, gen_tmpl, targs,
   3196 					      is_friend, 0);
   3197 	      remove_contract_attributes (result);
   3198 	      return decl;
   3199 	    }
   3200 
   3201 	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
   3202 	  DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
   3203 
   3204 	  if (was_template_id)
   3205 	    TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
   3206 
   3207 	  /* Inherit default function arguments from the template
   3208 	     DECL is specializing.  */
   3209 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl))
   3210 	    copy_default_args_to_explicit_spec (decl);
   3211 
   3212 	  /* This specialization has the same protection as the
   3213 	     template it specializes.  */
   3214 	  TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
   3215 	  TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
   3216 
   3217           /* 7.1.1-1 [dcl.stc]
   3218 
   3219              A storage-class-specifier shall not be specified in an
   3220              explicit specialization...
   3221 
   3222              The parser rejects these, so unless action is taken here,
   3223              explicit function specializations will always appear with
   3224              global linkage.
   3225 
   3226              The action recommended by the C++ CWG in response to C++
   3227              defect report 605 is to make the storage class and linkage
   3228              of the explicit specialization match the templated function:
   3229 
   3230              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
   3231            */
   3232           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
   3233             {
   3234               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
   3235               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
   3236 
   3237               /* A concept cannot be specialized.  */
   3238               if (DECL_DECLARED_CONCEPT_P (tmpl_func))
   3239                 {
   3240                   error ("explicit specialization of function concept %qD",
   3241                          gen_tmpl);
   3242                   return error_mark_node;
   3243                 }
   3244 
   3245               /* This specialization has the same linkage and visibility as
   3246                  the function template it specializes.  */
   3247               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
   3248 	      if (! TREE_PUBLIC (decl))
   3249 		{
   3250 		  DECL_INTERFACE_KNOWN (decl) = 1;
   3251 		  DECL_NOT_REALLY_EXTERN (decl) = 1;
   3252 		}
   3253               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
   3254               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
   3255                 {
   3256                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
   3257                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
   3258                 }
   3259             }
   3260 
   3261 	  /* If DECL is a friend declaration, declared using an
   3262 	     unqualified name, the namespace associated with DECL may
   3263 	     have been set incorrectly.  For example, in:
   3264 
   3265 	       template <typename T> void f(T);
   3266 	       namespace N {
   3267 		 struct S { friend void f<int>(int); }
   3268 	       }
   3269 
   3270 	     we will have set the DECL_CONTEXT for the friend
   3271 	     declaration to N, rather than to the global namespace.  */
   3272 	  if (DECL_NAMESPACE_SCOPE_P (decl))
   3273 	    DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
   3274 
   3275 	  if (is_friend && !have_def)
   3276 	    /* This is not really a declaration of a specialization.
   3277 	       It's just the name of an instantiation.  But, it's not
   3278 	       a request for an instantiation, either.  */
   3279 	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
   3280 	  else if (TREE_CODE (decl) == FUNCTION_DECL)
   3281 	    /* A specialization is not necessarily COMDAT.  */
   3282 	    DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
   3283 				  && DECL_DECLARED_INLINE_P (decl));
   3284 	  else if (VAR_P (decl))
   3285 	    DECL_COMDAT (decl) = false;
   3286 
   3287 	  /* If this is a full specialization, register it so that we can find
   3288 	     it again.  Partial specializations will be registered in
   3289 	     process_partial_specialization.  */
   3290 	  if (!processing_template_decl)
   3291 	    {
   3292 	      warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
   3293 
   3294 	      decl = register_specialization (decl, gen_tmpl, targs,
   3295 					      is_friend, 0);
   3296 	    }
   3297 
   3298 	  /* If this is a specialization, splice any contracts that may have
   3299 	     been inherited from the template, removing them.  */
   3300 	  if (decl != error_mark_node && DECL_TEMPLATE_SPECIALIZATION (decl))
   3301 	    remove_contract_attributes (decl);
   3302 
   3303 	  /* A 'structor should already have clones.  */
   3304 	  gcc_assert (decl == error_mark_node
   3305 		      || variable_template_p (tmpl)
   3306 		      || !(DECL_CONSTRUCTOR_P (decl)
   3307 			   || DECL_DESTRUCTOR_P (decl))
   3308 		      || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
   3309 	}
   3310     }
   3311 
   3312   return decl;
   3313 }
   3314 
   3315 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
   3316    parameters.  These are represented in the same format used for
   3317    DECL_TEMPLATE_PARMS.  */
   3318 
   3319 int
   3320 comp_template_parms (const_tree parms1, const_tree parms2)
   3321 {
   3322   if (parms1 == parms2)
   3323     return 1;
   3324 
   3325   tree t1 = TREE_VALUE (parms1);
   3326   tree t2 = TREE_VALUE (parms2);
   3327   int i;
   3328 
   3329   gcc_assert (TREE_CODE (t1) == TREE_VEC);
   3330   gcc_assert (TREE_CODE (t2) == TREE_VEC);
   3331 
   3332   if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
   3333     return 0;
   3334 
   3335   for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
   3336     {
   3337       tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
   3338       tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
   3339 
   3340       /* If either of the template parameters are invalid, assume
   3341 	 they match for the sake of error recovery. */
   3342       if (error_operand_p (parm1) || error_operand_p (parm2))
   3343 	return 1;
   3344 
   3345       if (TREE_CODE (parm1) != TREE_CODE (parm2))
   3346 	return 0;
   3347 
   3348       if (TREE_CODE (parm1) == TYPE_DECL
   3349 	  && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm1))
   3350 	      == TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm2))))
   3351 	continue;
   3352       else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
   3353 	return 0;
   3354     }
   3355 
   3356   return 1;
   3357 }
   3358 
   3359 /* Returns true if two template parameters are declared with
   3360    equivalent constraints.  */
   3361 
   3362 static bool
   3363 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
   3364 {
   3365   tree req1 = TREE_TYPE (parm1);
   3366   tree req2 = TREE_TYPE (parm2);
   3367   if (!req1 != !req2)
   3368     return false;
   3369   if (req1)
   3370     return cp_tree_equal (req1, req2);
   3371   return true;
   3372 }
   3373 
   3374 /* Returns true when two template parameters are equivalent.  */
   3375 
   3376 static bool
   3377 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
   3378 {
   3379   tree decl1 = TREE_VALUE (parm1);
   3380   tree decl2 = TREE_VALUE (parm2);
   3381 
   3382   /* If either of the template parameters are invalid, assume
   3383      they match for the sake of error recovery. */
   3384   if (error_operand_p (decl1) || error_operand_p (decl2))
   3385     return true;
   3386 
   3387   /* ... they declare parameters of the same kind.  */
   3388   if (TREE_CODE (decl1) != TREE_CODE (decl2))
   3389     return false;
   3390 
   3391   /* ... one parameter was introduced by a parameter declaration, then
   3392      both are. This case arises as a result of eagerly rewriting declarations
   3393      during parsing.  */
   3394   if (DECL_IMPLICIT_TEMPLATE_PARM_P (decl1)
   3395       != DECL_IMPLICIT_TEMPLATE_PARM_P (decl2))
   3396     return false;
   3397 
   3398   /* ... if either declares a pack, they both do.  */
   3399   if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
   3400     return false;
   3401 
   3402   if (TREE_CODE (decl1) == PARM_DECL)
   3403     {
   3404       /* ... if they declare non-type parameters, the types are equivalent.  */
   3405       if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
   3406 	return false;
   3407     }
   3408   else if (TREE_CODE (decl2) == TEMPLATE_DECL)
   3409     {
   3410       /* ... if they declare template template parameters, their template
   3411 	 parameter lists are equivalent.  */
   3412       if (!template_heads_equivalent_p (decl1, decl2))
   3413 	return false;
   3414     }
   3415 
   3416   /* ... if they are declared with a qualified-concept name, they both
   3417      are, and those names are equivalent.  */
   3418   return template_parameter_constraints_equivalent_p (parm1, parm2);
   3419 }
   3420 
   3421 /* Returns true if two template parameters lists are equivalent.
   3422    Two template parameter lists are equivalent if they have the
   3423    same length and their corresponding parameters are equivalent.
   3424 
   3425    PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
   3426    data structure returned by DECL_TEMPLATE_PARMS.
   3427 
   3428    This is generally the same implementation as comp_template_parms
   3429    except that it also the concept names and arguments used to
   3430    introduce parameters.  */
   3431 
   3432 static bool
   3433 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
   3434 {
   3435   if (parms1 == parms2)
   3436     return true;
   3437 
   3438   tree list1 = TREE_VALUE (parms1);
   3439   tree list2 = TREE_VALUE (parms2);
   3440 
   3441   if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
   3442     return 0;
   3443 
   3444   for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
   3445     {
   3446       tree parm1 = TREE_VEC_ELT (list1, i);
   3447       tree parm2 = TREE_VEC_ELT (list2, i);
   3448       if (!template_parameters_equivalent_p (parm1, parm2))
   3449 	return false;
   3450     }
   3451 
   3452   return true;
   3453 }
   3454 
   3455 /* Return true if the requires-clause of the template parameter lists are
   3456    equivalent and false otherwise.  */
   3457 static bool
   3458 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
   3459 {
   3460   tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
   3461   tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
   3462   if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
   3463     return false;
   3464   if (!cp_tree_equal (req1, req2))
   3465     return false;
   3466   return true;
   3467 }
   3468 
   3469 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
   3470    Two template heads are equivalent if their template parameter
   3471    lists are equivalent and their requires clauses are equivalent.
   3472 
   3473    In pre-C++20, this is equivalent to calling comp_template_parms
   3474    for the template parameters of TMPL1 and TMPL2.  */
   3475 
   3476 bool
   3477 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
   3478 {
   3479   tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
   3480   tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
   3481 
   3482   /* Don't change the matching rules for pre-C++20.  */
   3483   if (cxx_dialect < cxx20)
   3484     return comp_template_parms (parms1, parms2);
   3485 
   3486   /* ... have the same number of template parameters, and their
   3487      corresponding parameters are equivalent.  */
   3488   if (!template_parameter_lists_equivalent_p (parms1, parms2))
   3489     return false;
   3490 
   3491   /* ... if either has a requires-clause, they both do and their
   3492      corresponding constraint-expressions are equivalent.  */
   3493   return template_requirements_equivalent_p (parms1, parms2);
   3494 }
   3495 
   3496 /* Determine whether PARM is a parameter pack.  */
   3497 
   3498 bool
   3499 template_parameter_pack_p (const_tree parm)
   3500 {
   3501   /* Determine if we have a non-type template parameter pack.  */
   3502   if (TREE_CODE (parm) == PARM_DECL)
   3503     return (DECL_TEMPLATE_PARM_P (parm)
   3504             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
   3505   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
   3506     return TEMPLATE_PARM_PARAMETER_PACK (parm);
   3507 
   3508   /* If this is a list of template parameters, we could get a
   3509      TYPE_DECL or a TEMPLATE_DECL.  */
   3510   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
   3511     parm = TREE_TYPE (parm);
   3512 
   3513   /* Otherwise it must be a type template parameter.  */
   3514   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
   3515 	   || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
   3516 	  && TEMPLATE_TYPE_PARAMETER_PACK (parm));
   3517 }
   3518 
   3519 /* Determine if T is a function parameter pack.  */
   3520 
   3521 bool
   3522 function_parameter_pack_p (const_tree t)
   3523 {
   3524   if (t && TREE_CODE (t) == PARM_DECL)
   3525     return DECL_PACK_P (t);
   3526   return false;
   3527 }
   3528 
   3529 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
   3530    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
   3531 
   3532 tree
   3533 get_function_template_decl (const_tree primary_func_tmpl_inst)
   3534 {
   3535   if (! primary_func_tmpl_inst
   3536       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
   3537       || ! primary_template_specialization_p (primary_func_tmpl_inst))
   3538     return NULL;
   3539 
   3540   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
   3541 }
   3542 
   3543 /* Return true iff the function parameter PARAM_DECL was expanded
   3544    from the function parameter pack PACK.  */
   3545 
   3546 bool
   3547 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
   3548 {
   3549   if (DECL_ARTIFICIAL (param_decl)
   3550       || !function_parameter_pack_p (pack))
   3551     return false;
   3552 
   3553   /* The parameter pack and its pack arguments have the same
   3554      DECL_PARM_INDEX.  */
   3555   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
   3556 }
   3557 
   3558 /* Determine whether ARGS describes a variadic template args list,
   3559    i.e., one that is terminated by a template argument pack.  */
   3560 
   3561 static bool
   3562 template_args_variadic_p (tree args)
   3563 {
   3564   int nargs;
   3565   tree last_parm;
   3566 
   3567   if (args == NULL_TREE)
   3568     return false;
   3569 
   3570   args = INNERMOST_TEMPLATE_ARGS (args);
   3571   nargs = TREE_VEC_LENGTH (args);
   3572 
   3573   if (nargs == 0)
   3574     return false;
   3575 
   3576   last_parm = TREE_VEC_ELT (args, nargs - 1);
   3577 
   3578   return ARGUMENT_PACK_P (last_parm);
   3579 }
   3580 
   3581 /* Generate a new name for the parameter pack name NAME (an
   3582    IDENTIFIER_NODE) that incorporates its */
   3583 
   3584 static tree
   3585 make_ith_pack_parameter_name (tree name, int i)
   3586 {
   3587   /* Munge the name to include the parameter index.  */
   3588 #define NUMBUF_LEN 128
   3589   char numbuf[NUMBUF_LEN];
   3590   char* newname;
   3591   int newname_len;
   3592 
   3593   if (name == NULL_TREE)
   3594     return name;
   3595   snprintf (numbuf, NUMBUF_LEN, "%i", i);
   3596   newname_len = IDENTIFIER_LENGTH (name)
   3597 	        + strlen (numbuf) + 2;
   3598   newname = (char*)alloca (newname_len);
   3599   snprintf (newname, newname_len,
   3600 	    "%s#%i", IDENTIFIER_POINTER (name), i);
   3601   return get_identifier (newname);
   3602 }
   3603 
   3604 /* Return true if T is a primary function, class or alias template
   3605    specialization, not including the template pattern.  */
   3606 
   3607 bool
   3608 primary_template_specialization_p (const_tree t)
   3609 {
   3610   if (!t)
   3611     return false;
   3612 
   3613   if (VAR_OR_FUNCTION_DECL_P (t))
   3614     return (DECL_LANG_SPECIFIC (t)
   3615 	    && DECL_USE_TEMPLATE (t)
   3616 	    && DECL_TEMPLATE_INFO (t)
   3617 	    && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
   3618   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
   3619     return (CLASSTYPE_TEMPLATE_INFO (t)
   3620 	    && CLASSTYPE_USE_TEMPLATE (t)
   3621 	    && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
   3622   else if (alias_template_specialization_p (t, nt_transparent))
   3623     return true;
   3624   return false;
   3625 }
   3626 
   3627 /* Return true if PARM is a template template parameter.  */
   3628 
   3629 bool
   3630 template_template_parameter_p (const_tree parm)
   3631 {
   3632   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
   3633 }
   3634 
   3635 /* Return true iff PARM is a DECL representing a type template
   3636    parameter.  */
   3637 
   3638 bool
   3639 template_type_parameter_p (const_tree parm)
   3640 {
   3641   return (parm
   3642 	  && (TREE_CODE (parm) == TYPE_DECL
   3643 	      || TREE_CODE (parm) == TEMPLATE_DECL)
   3644 	  && DECL_TEMPLATE_PARM_P (parm));
   3645 }
   3646 
   3647 /* Return the template parameters of T if T is a
   3648    primary template instantiation, NULL otherwise.  */
   3649 
   3650 tree
   3651 get_primary_template_innermost_parameters (const_tree t)
   3652 {
   3653   tree parms = NULL, template_info = NULL;
   3654 
   3655   if ((template_info = get_template_info (t))
   3656       && primary_template_specialization_p (t))
   3657     parms = INNERMOST_TEMPLATE_PARMS
   3658 	(DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
   3659 
   3660   return parms;
   3661 }
   3662 
   3663 /* Returns the template arguments of T if T is a template instantiation,
   3664    NULL otherwise.  */
   3665 
   3666 tree
   3667 get_template_innermost_arguments (const_tree t)
   3668 {
   3669   tree args = NULL, template_info = NULL;
   3670 
   3671   if ((template_info = get_template_info (t))
   3672       && TI_ARGS (template_info))
   3673     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
   3674 
   3675   return args;
   3676 }
   3677 
   3678 /* Return the argument pack elements of T if T is a template argument pack,
   3679    NULL otherwise.  */
   3680 
   3681 tree
   3682 get_template_argument_pack_elems (const_tree t)
   3683 {
   3684   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
   3685       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
   3686     return NULL;
   3687 
   3688   return ARGUMENT_PACK_ARGS (t);
   3689 }
   3690 
   3691 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
   3692    ARGUMENT_PACK_SELECT represents. */
   3693 
   3694 static tree
   3695 argument_pack_select_arg (tree t)
   3696 {
   3697   tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
   3698   tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
   3699 
   3700   /* If the selected argument is an expansion E, that most likely means we were
   3701      called from gen_elem_of_pack_expansion_instantiation during the
   3702      substituting of an argument pack (of which the Ith element is a pack
   3703      expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
   3704      In this case, the Ith element resulting from this substituting is going to
   3705      be a pack expansion, which pattern is the pattern of E.  Let's return the
   3706      pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
   3707      resulting pack expansion from it.  */
   3708   if (PACK_EXPANSION_P (arg))
   3709     {
   3710       /* Make sure we aren't throwing away arg info.  */
   3711       gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
   3712       arg = PACK_EXPANSION_PATTERN (arg);
   3713     }
   3714 
   3715   return arg;
   3716 }
   3717 
   3718 /* Return a modification of ARGS that's suitable for preserving inside a hash
   3719    table.  In particular, this replaces each ARGUMENT_PACK_SELECT with its
   3720    underlying argument.  ARGS is copied (upon modification) iff COW_P.  */
   3721 
   3722 static tree
   3723 preserve_args (tree args, bool cow_p = true)
   3724 {
   3725   if (!args)
   3726     return NULL_TREE;
   3727 
   3728   for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
   3729     {
   3730       tree t = TREE_VEC_ELT (args, i);
   3731       tree r;
   3732       if (!t)
   3733 	r = NULL_TREE;
   3734       else if (TREE_CODE (t) == ARGUMENT_PACK_SELECT)
   3735 	r = argument_pack_select_arg (t);
   3736       else if (TREE_CODE (t) == TREE_VEC)
   3737 	r = preserve_args (t, cow_p);
   3738       else
   3739 	r = t;
   3740       if (r != t)
   3741 	{
   3742 	  if (cow_p)
   3743 	    {
   3744 	      args = copy_template_args (args);
   3745 	      cow_p = false;
   3746 	    }
   3747 	  TREE_VEC_ELT (args, i) = r;
   3748 	}
   3749     }
   3750 
   3751   return args;
   3752 }
   3753 
   3754 /* True iff FN is a function representing a built-in variadic parameter
   3755    pack.  */
   3756 
   3757 bool
   3758 builtin_pack_fn_p (tree fn)
   3759 {
   3760   if (!fn
   3761       || TREE_CODE (fn) != FUNCTION_DECL
   3762       || !DECL_IS_UNDECLARED_BUILTIN (fn))
   3763     return false;
   3764 
   3765   if (id_equal (DECL_NAME (fn), "__integer_pack"))
   3766     return true;
   3767 
   3768   return false;
   3769 }
   3770 
   3771 /* True iff CALL is a call to a function representing a built-in variadic
   3772    parameter pack.  */
   3773 
   3774 static bool
   3775 builtin_pack_call_p (tree call)
   3776 {
   3777   if (TREE_CODE (call) != CALL_EXPR)
   3778     return false;
   3779   return builtin_pack_fn_p (CALL_EXPR_FN (call));
   3780 }
   3781 
   3782 /* Return a TREE_VEC for the expansion of __integer_pack(HI).  */
   3783 
   3784 static tree
   3785 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
   3786 		     tree in_decl)
   3787 {
   3788   tree ohi = CALL_EXPR_ARG (call, 0);
   3789   tree hi = tsubst_expr (ohi, args, complain, in_decl);
   3790 
   3791   if (instantiation_dependent_expression_p (hi))
   3792     {
   3793       if (hi != ohi)
   3794 	{
   3795 	  call = copy_node (call);
   3796 	  CALL_EXPR_ARG (call, 0) = hi;
   3797 	}
   3798       tree ex = make_pack_expansion (call, complain);
   3799       tree vec = make_tree_vec (1);
   3800       TREE_VEC_ELT (vec, 0) = ex;
   3801       return vec;
   3802     }
   3803   else
   3804     {
   3805       hi = instantiate_non_dependent_expr (hi, complain);
   3806       hi = cxx_constant_value (hi, complain);
   3807       int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
   3808 
   3809       /* Calculate the largest value of len that won't make the size of the vec
   3810 	 overflow an int.  The compiler will exceed resource limits long before
   3811 	 this, but it seems a decent place to diagnose.  */
   3812       int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
   3813 
   3814       if (len < 0 || len > max)
   3815 	{
   3816 	  if ((complain & tf_error)
   3817 	      && hi != error_mark_node)
   3818 	    error ("argument to %<__integer_pack%> must be between 0 and %d",
   3819 		   max);
   3820 	  return error_mark_node;
   3821 	}
   3822 
   3823       tree vec = make_tree_vec (len);
   3824 
   3825       for (int i = 0; i < len; ++i)
   3826 	TREE_VEC_ELT (vec, i) = size_int (i);
   3827 
   3828       return vec;
   3829     }
   3830 }
   3831 
   3832 /* Return a TREE_VEC for the expansion of built-in template parameter pack
   3833    CALL.  */
   3834 
   3835 static tree
   3836 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
   3837 			  tree in_decl)
   3838 {
   3839   if (!builtin_pack_call_p (call))
   3840     return NULL_TREE;
   3841 
   3842   tree fn = CALL_EXPR_FN (call);
   3843 
   3844   if (id_equal (DECL_NAME (fn), "__integer_pack"))
   3845     return expand_integer_pack (call, args, complain, in_decl);
   3846 
   3847   return NULL_TREE;
   3848 }
   3849 
   3850 /* Return true if the tree T has the extra args mechanism for
   3851    avoiding partial instantiation.  */
   3852 
   3853 static bool
   3854 has_extra_args_mechanism_p (const_tree t)
   3855 {
   3856   return (PACK_EXPANSION_P (t) /* PACK_EXPANSION_EXTRA_ARGS  */
   3857 	  || TREE_CODE (t) == REQUIRES_EXPR /* REQUIRES_EXPR_EXTRA_ARGS  */
   3858 	  || (TREE_CODE (t) == IF_STMT
   3859 	      && IF_STMT_CONSTEXPR_P (t)) /* IF_STMT_EXTRA_ARGS  */
   3860 	  || TREE_CODE (t) == LAMBDA_EXPR); /* LAMBDA_EXPR_EXTRA_ARGS  */
   3861 }
   3862 
   3863 /* Return *_EXTRA_ARGS of the given supported tree T.  */
   3864 
   3865 static tree&
   3866 tree_extra_args (tree t)
   3867 {
   3868   gcc_checking_assert (has_extra_args_mechanism_p (t));
   3869 
   3870   if (PACK_EXPANSION_P (t))
   3871     return PACK_EXPANSION_EXTRA_ARGS (t);
   3872   else if (TREE_CODE (t) == REQUIRES_EXPR)
   3873     return REQUIRES_EXPR_EXTRA_ARGS (t);
   3874   else if (TREE_CODE (t) == IF_STMT
   3875 	   && IF_STMT_CONSTEXPR_P (t))
   3876     return IF_STMT_EXTRA_ARGS (t);
   3877   else if (TREE_CODE (t) == LAMBDA_EXPR)
   3878     return LAMBDA_EXPR_EXTRA_ARGS (t);
   3879 
   3880   gcc_unreachable ();
   3881 }
   3882 
   3883 /* Structure used to track the progress of find_parameter_packs_r.  */
   3884 struct find_parameter_pack_data
   3885 {
   3886   /* TREE_LIST that will contain all of the parameter packs found by
   3887      the traversal.  */
   3888   tree* parameter_packs;
   3889 
   3890   /* Set of AST nodes that have been visited by the traversal.  */
   3891   hash_set<tree> *visited;
   3892 
   3893   /* True iff we're making a type pack expansion.  */
   3894   bool type_pack_expansion_p;
   3895 
   3896   /* True iff we found a subtree that has the extra args mechanism.  */
   3897   bool found_extra_args_tree_p = false;
   3898 };
   3899 
   3900 /* Identifies all of the argument packs that occur in a template
   3901    argument and appends them to the TREE_LIST inside DATA, which is a
   3902    find_parameter_pack_data structure. This is a subroutine of
   3903    make_pack_expansion and uses_parameter_packs.  */
   3904 static tree
   3905 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
   3906 {
   3907   tree t = *tp;
   3908   struct find_parameter_pack_data* ppd =
   3909     (struct find_parameter_pack_data*)data;
   3910   bool parameter_pack_p = false;
   3911 
   3912 #define WALK_SUBTREE(NODE)				\
   3913   cp_walk_tree (&(NODE), &find_parameter_packs_r,	\
   3914 		ppd, ppd->visited)			\
   3915 
   3916   /* Don't look through typedefs; we are interested in whether a
   3917      parameter pack is actually written in the expression/type we're
   3918      looking at, not the target type.  */
   3919   if (TYPE_P (t) && typedef_variant_p (t))
   3920     {
   3921       /* But do look at arguments for an alias template.  */
   3922       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
   3923 	cp_walk_tree (&TI_ARGS (tinfo),
   3924 		      &find_parameter_packs_r,
   3925 		      ppd, ppd->visited);
   3926       *walk_subtrees = 0;
   3927       return NULL_TREE;
   3928     }
   3929 
   3930   /* Identify whether this is a parameter pack or not.  */
   3931   switch (TREE_CODE (t))
   3932     {
   3933     case TEMPLATE_PARM_INDEX:
   3934       if (TEMPLATE_PARM_PARAMETER_PACK (t))
   3935         parameter_pack_p = true;
   3936       break;
   3937 
   3938     case TEMPLATE_TYPE_PARM:
   3939       t = TYPE_MAIN_VARIANT (t);
   3940       /* FALLTHRU */
   3941     case TEMPLATE_TEMPLATE_PARM:
   3942       /* If the placeholder appears in the decl-specifier-seq of a function
   3943 	 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
   3944 	 is a pack expansion, the invented template parameter is a template
   3945 	 parameter pack.  */
   3946       if (flag_concepts_ts && ppd->type_pack_expansion_p && is_auto (t)
   3947 	  && TEMPLATE_TYPE_LEVEL (t) != 0)
   3948 	TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
   3949       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
   3950         parameter_pack_p = true;
   3951       break;
   3952 
   3953     case FIELD_DECL:
   3954     case PARM_DECL:
   3955       if (DECL_PACK_P (t))
   3956         {
   3957           /* We don't want to walk into the type of a PARM_DECL,
   3958              because we don't want to see the type parameter pack.  */
   3959           *walk_subtrees = 0;
   3960 	  parameter_pack_p = true;
   3961         }
   3962       break;
   3963 
   3964     case VAR_DECL:
   3965       if (DECL_PACK_P (t))
   3966         {
   3967           /* We don't want to walk into the type of a variadic capture proxy,
   3968              because we don't want to see the type parameter pack.  */
   3969           *walk_subtrees = 0;
   3970 	  parameter_pack_p = true;
   3971         }
   3972       else if (variable_template_specialization_p (t))
   3973 	{
   3974 	  cp_walk_tree (&DECL_TI_ARGS (t),
   3975 			find_parameter_packs_r,
   3976 			ppd, ppd->visited);
   3977 	  *walk_subtrees = 0;
   3978 	}
   3979       break;
   3980 
   3981     case CALL_EXPR:
   3982       if (builtin_pack_call_p (t))
   3983 	parameter_pack_p = true;
   3984       break;
   3985 
   3986     case BASES:
   3987       parameter_pack_p = true;
   3988       break;
   3989     default:
   3990       /* Not a parameter pack.  */
   3991       break;
   3992     }
   3993 
   3994   if (parameter_pack_p)
   3995     {
   3996       /* Add this parameter pack to the list.  */
   3997       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
   3998     }
   3999 
   4000   if (has_extra_args_mechanism_p (t) && !PACK_EXPANSION_P (t))
   4001     ppd->found_extra_args_tree_p = true;
   4002 
   4003   if (TYPE_P (t))
   4004     cp_walk_tree (&TYPE_CONTEXT (t),
   4005 		  &find_parameter_packs_r, ppd, ppd->visited);
   4006 
   4007   /* This switch statement will return immediately if we don't find a
   4008      parameter pack.  ??? Should some of these be in cp_walk_subtrees?  */
   4009   switch (TREE_CODE (t))
   4010     {
   4011     case BOUND_TEMPLATE_TEMPLATE_PARM:
   4012       /* Check the template itself.  */
   4013       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
   4014 		    &find_parameter_packs_r, ppd, ppd->visited);
   4015       return NULL_TREE;
   4016 
   4017     case DECL_EXPR:
   4018       {
   4019 	tree decl = DECL_EXPR_DECL (t);
   4020 	/* Ignore the declaration of a capture proxy for a parameter pack.  */
   4021 	if (is_capture_proxy (decl))
   4022 	  *walk_subtrees = 0;
   4023 	if (is_typedef_decl (decl))
   4024 	  /* Since we stop at typedefs above, we need to look through them at
   4025 	     the point of the DECL_EXPR.  */
   4026 	  cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
   4027 			&find_parameter_packs_r, ppd, ppd->visited);
   4028 	return NULL_TREE;
   4029       }
   4030 
   4031     case TEMPLATE_DECL:
   4032       if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
   4033 	return NULL_TREE;
   4034       cp_walk_tree (&TREE_TYPE (t),
   4035 		    &find_parameter_packs_r, ppd, ppd->visited);
   4036       return NULL_TREE;
   4037 
   4038     case TYPE_PACK_EXPANSION:
   4039     case EXPR_PACK_EXPANSION:
   4040       *walk_subtrees = 0;
   4041       return NULL_TREE;
   4042 
   4043     case INTEGER_TYPE:
   4044       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
   4045 		    ppd, ppd->visited);
   4046       *walk_subtrees = 0;
   4047       return NULL_TREE;
   4048 
   4049     case IDENTIFIER_NODE:
   4050       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
   4051 		    ppd->visited);
   4052       *walk_subtrees = 0;
   4053       return NULL_TREE;
   4054 
   4055     case LAMBDA_EXPR:
   4056       {
   4057 	/* Since we defer implicit capture, look in the parms and body.  */
   4058 	tree fn = lambda_function (t);
   4059 	cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
   4060 		      ppd->visited);
   4061 	cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
   4062 		      ppd->visited);
   4063 	return NULL_TREE;
   4064       }
   4065 
   4066     case DECLTYPE_TYPE:
   4067       {
   4068 	/* When traversing a DECLTYPE_TYPE_EXPR, we need to set
   4069 	   type_pack_expansion_p to false so that any placeholders
   4070 	   within the expression don't get marked as parameter packs.  */
   4071 	bool type_pack_expansion_p = ppd->type_pack_expansion_p;
   4072 	ppd->type_pack_expansion_p = false;
   4073 	cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
   4074 		      ppd, ppd->visited);
   4075 	ppd->type_pack_expansion_p = type_pack_expansion_p;
   4076 	*walk_subtrees = 0;
   4077 	return NULL_TREE;
   4078       }
   4079 
   4080     case IF_STMT:
   4081       cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
   4082 		    ppd, ppd->visited);
   4083       cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
   4084 		    ppd, ppd->visited);
   4085       cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
   4086 		    ppd, ppd->visited);
   4087       /* Don't walk into IF_STMT_EXTRA_ARGS.  */
   4088       *walk_subtrees = 0;
   4089       return NULL_TREE;
   4090 
   4091     case TAG_DEFN:
   4092       t = TREE_TYPE (t);
   4093       if (CLASS_TYPE_P (t))
   4094 	{
   4095 	  /* Local class, need to look through the whole definition.
   4096 	     TYPE_BINFO might be unset for a partial instantiation.  */
   4097 	  if (TYPE_BINFO (t))
   4098 	    for (tree bb : BINFO_BASE_BINFOS (TYPE_BINFO (t)))
   4099 	      cp_walk_tree (&BINFO_TYPE (bb), &find_parameter_packs_r,
   4100 			    ppd, ppd->visited);
   4101 	}
   4102       else
   4103 	/* Enum, look at the values.  */
   4104 	for (tree l = TYPE_VALUES (t); l; l = TREE_CHAIN (l))
   4105 	  cp_walk_tree (&DECL_INITIAL (TREE_VALUE (l)),
   4106 			&find_parameter_packs_r,
   4107 			ppd, ppd->visited);
   4108       return NULL_TREE;
   4109 
   4110     case FUNCTION_TYPE:
   4111     case METHOD_TYPE:
   4112       WALK_SUBTREE (TYPE_RAISES_EXCEPTIONS (t));
   4113       break;
   4114 
   4115     default:
   4116       return NULL_TREE;
   4117     }
   4118 
   4119 #undef WALK_SUBTREE
   4120 
   4121   return NULL_TREE;
   4122 }
   4123 
   4124 /* Determines if the expression or type T uses any parameter packs.  */
   4125 tree
   4126 uses_parameter_packs (tree t)
   4127 {
   4128   tree parameter_packs = NULL_TREE;
   4129   struct find_parameter_pack_data ppd;
   4130   ppd.parameter_packs = &parameter_packs;
   4131   ppd.visited = new hash_set<tree>;
   4132   ppd.type_pack_expansion_p = false;
   4133   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
   4134   delete ppd.visited;
   4135   return parameter_packs;
   4136 }
   4137 
   4138 /* Turn ARG, which may be an expression, type, or a TREE_LIST
   4139    representation a base-class initializer into a parameter pack
   4140    expansion. If all goes well, the resulting node will be an
   4141    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
   4142    respectively.  */
   4143 tree
   4144 make_pack_expansion (tree arg, tsubst_flags_t complain)
   4145 {
   4146   tree result;
   4147   tree parameter_packs = NULL_TREE;
   4148   bool for_types = false;
   4149   struct find_parameter_pack_data ppd;
   4150 
   4151   if (!arg || arg == error_mark_node)
   4152     return arg;
   4153 
   4154   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
   4155     {
   4156       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
   4157          class initializer.  In this case, the TREE_PURPOSE will be a
   4158          _TYPE node (representing the base class expansion we're
   4159          initializing) and the TREE_VALUE will be a TREE_LIST
   4160          containing the initialization arguments.
   4161 
   4162          The resulting expansion looks somewhat different from most
   4163          expansions. Rather than returning just one _EXPANSION, we
   4164          return a TREE_LIST whose TREE_PURPOSE is a
   4165          TYPE_PACK_EXPANSION containing the bases that will be
   4166          initialized.  The TREE_VALUE will be identical to the
   4167          original TREE_VALUE, which is a list of arguments that will
   4168          be passed to each base.  We do not introduce any new pack
   4169          expansion nodes into the TREE_VALUE (although it is possible
   4170          that some already exist), because the TREE_PURPOSE and
   4171          TREE_VALUE all need to be expanded together with the same
   4172          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
   4173          resulting TREE_PURPOSE will mention the parameter packs in
   4174          both the bases and the arguments to the bases.  */
   4175       tree purpose;
   4176       tree value;
   4177       tree parameter_packs = NULL_TREE;
   4178 
   4179       /* Determine which parameter packs will be used by the base
   4180          class expansion.  */
   4181       ppd.visited = new hash_set<tree>;
   4182       ppd.parameter_packs = &parameter_packs;
   4183       ppd.type_pack_expansion_p = false;
   4184       gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
   4185       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
   4186                     &ppd, ppd.visited);
   4187 
   4188       if (parameter_packs == NULL_TREE)
   4189         {
   4190 	  if (complain & tf_error)
   4191 	    error ("base initializer expansion %qT contains no parameter packs",
   4192 		   arg);
   4193           delete ppd.visited;
   4194           return error_mark_node;
   4195         }
   4196 
   4197       if (TREE_VALUE (arg) != void_type_node)
   4198         {
   4199           /* Collect the sets of parameter packs used in each of the
   4200              initialization arguments.  */
   4201           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
   4202             {
   4203               /* Determine which parameter packs will be expanded in this
   4204                  argument.  */
   4205               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
   4206                             &ppd, ppd.visited);
   4207             }
   4208         }
   4209 
   4210       delete ppd.visited;
   4211 
   4212       /* Create the pack expansion type for the base type.  */
   4213       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
   4214       PACK_EXPANSION_PATTERN (purpose) = TREE_PURPOSE (arg);
   4215       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
   4216       PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
   4217 
   4218       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
   4219 	 they will rarely be compared to anything.  */
   4220       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
   4221 
   4222       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
   4223     }
   4224 
   4225   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
   4226     for_types = true;
   4227 
   4228   /* Build the PACK_EXPANSION_* node.  */
   4229   result = for_types
   4230      ? cxx_make_type (TYPE_PACK_EXPANSION)
   4231      : make_node (EXPR_PACK_EXPANSION);
   4232   PACK_EXPANSION_PATTERN (result) = arg;
   4233   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
   4234     {
   4235       /* Propagate type and const-expression information.  */
   4236       TREE_TYPE (result) = TREE_TYPE (arg);
   4237       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
   4238       /* Mark this read now, since the expansion might be length 0.  */
   4239       mark_exp_read (arg);
   4240     }
   4241   else
   4242     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
   4243        they will rarely be compared to anything.  */
   4244     SET_TYPE_STRUCTURAL_EQUALITY (result);
   4245 
   4246   /* Determine which parameter packs will be expanded.  */
   4247   ppd.parameter_packs = &parameter_packs;
   4248   ppd.visited = new hash_set<tree>;
   4249   ppd.type_pack_expansion_p = TYPE_P (arg);
   4250   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
   4251   delete ppd.visited;
   4252 
   4253   /* Make sure we found some parameter packs.  */
   4254   if (parameter_packs == NULL_TREE)
   4255     {
   4256       if (complain & tf_error)
   4257 	{
   4258 	  if (TYPE_P (arg))
   4259 	    error ("expansion pattern %qT contains no parameter packs", arg);
   4260 	  else
   4261 	    error ("expansion pattern %qE contains no parameter packs", arg);
   4262 	}
   4263       return error_mark_node;
   4264     }
   4265   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
   4266 
   4267   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
   4268   if (ppd.found_extra_args_tree_p)
   4269     /* If the pattern of this pack expansion contains a subtree that has
   4270        the extra args mechanism for avoiding partial instantiation, then
   4271        force this pack expansion to also use extra args.  Otherwise
   4272        partial instantiation of this pack expansion may not lower the
   4273        level of some parameter packs within the pattern, which would
   4274        confuse tsubst_pack_expansion later (PR101764).  */
   4275     PACK_EXPANSION_FORCE_EXTRA_ARGS_P (result) = true;
   4276 
   4277   return result;
   4278 }
   4279 
   4280 /* Checks T for any "bare" parameter packs, which have not yet been
   4281    expanded, and issues an error if any are found. This operation can
   4282    only be done on full expressions or types (e.g., an expression
   4283    statement, "if" condition, etc.), because we could have expressions like:
   4284 
   4285      foo(f(g(h(args)))...)
   4286 
   4287    where "args" is a parameter pack. check_for_bare_parameter_packs
   4288    should not be called for the subexpressions args, h(args),
   4289    g(h(args)), or f(g(h(args))), because we would produce erroneous
   4290    error messages.
   4291 
   4292    Returns TRUE and emits an error if there were bare parameter packs,
   4293    returns FALSE otherwise.  */
   4294 bool
   4295 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
   4296 {
   4297   tree parameter_packs = NULL_TREE;
   4298   struct find_parameter_pack_data ppd;
   4299 
   4300   if (!processing_template_decl || !t || t == error_mark_node)
   4301     return false;
   4302 
   4303   if (TREE_CODE (t) == TYPE_DECL)
   4304     t = TREE_TYPE (t);
   4305 
   4306   ppd.parameter_packs = &parameter_packs;
   4307   ppd.visited = new hash_set<tree>;
   4308   ppd.type_pack_expansion_p = false;
   4309   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
   4310   delete ppd.visited;
   4311 
   4312   if (!parameter_packs)
   4313     return false;
   4314 
   4315   if (loc == UNKNOWN_LOCATION)
   4316     loc = cp_expr_loc_or_input_loc (t);
   4317 
   4318   /* It's OK for a lambda to have an unexpanded parameter pack from the
   4319      containing context, but do complain about unexpanded capture packs.  */
   4320   tree lam = current_lambda_expr ();
   4321   if (lam)
   4322     lam = TREE_TYPE (lam);
   4323 
   4324   if (lam && lam != current_class_type)
   4325     {
   4326       /* We're in a lambda, but it isn't the innermost class.
   4327 	 This should work, but currently doesn't.  */
   4328       sorry_at (loc, "unexpanded parameter pack in local class in lambda");
   4329       return true;
   4330     }
   4331 
   4332   if (lam && CLASSTYPE_TEMPLATE_INFO (lam))
   4333     for (; parameter_packs;
   4334 	 parameter_packs = TREE_CHAIN (parameter_packs))
   4335       {
   4336 	tree pack = TREE_VALUE (parameter_packs);
   4337 	if (is_capture_proxy (pack)
   4338 	    || (TREE_CODE (pack) == PARM_DECL
   4339 		&& DECL_CONTEXT (pack)
   4340 		&& DECL_CONTEXT (DECL_CONTEXT (pack)) == lam))
   4341 	  break;
   4342       }
   4343 
   4344   if (parameter_packs)
   4345     {
   4346       error_at (loc, "parameter packs not expanded with %<...%>:");
   4347       while (parameter_packs)
   4348         {
   4349           tree pack = TREE_VALUE (parameter_packs);
   4350           tree name = NULL_TREE;
   4351 
   4352           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
   4353               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
   4354             name = TYPE_NAME (pack);
   4355           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
   4356             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
   4357 	  else if (TREE_CODE (pack) == CALL_EXPR)
   4358 	    name = DECL_NAME (CALL_EXPR_FN (pack));
   4359           else
   4360             name = DECL_NAME (pack);
   4361 
   4362 	  if (name)
   4363 	    inform (loc, "        %qD", name);
   4364 	  else
   4365 	    inform (loc, "        %s", "<anonymous>");
   4366 
   4367           parameter_packs = TREE_CHAIN (parameter_packs);
   4368         }
   4369 
   4370       return true;
   4371     }
   4372 
   4373   return false;
   4374 }
   4375 
   4376 /* Expand any parameter packs that occur in the template arguments in
   4377    ARGS.  */
   4378 tree
   4379 expand_template_argument_pack (tree args)
   4380 {
   4381   if (args == error_mark_node)
   4382     return error_mark_node;
   4383 
   4384   tree result_args = NULL_TREE;
   4385   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
   4386   int num_result_args = -1;
   4387   int non_default_args_count = -1;
   4388 
   4389   /* First, determine if we need to expand anything, and the number of
   4390      slots we'll need.  */
   4391   for (in_arg = 0; in_arg < nargs; ++in_arg)
   4392     {
   4393       tree arg = TREE_VEC_ELT (args, in_arg);
   4394       if (arg == NULL_TREE)
   4395 	return args;
   4396       if (ARGUMENT_PACK_P (arg))
   4397         {
   4398           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
   4399           if (num_result_args < 0)
   4400             num_result_args = in_arg + num_packed;
   4401           else
   4402             num_result_args += num_packed;
   4403         }
   4404       else
   4405         {
   4406           if (num_result_args >= 0)
   4407             num_result_args++;
   4408         }
   4409     }
   4410 
   4411   /* If no expansion is necessary, we're done.  */
   4412   if (num_result_args < 0)
   4413     return args;
   4414 
   4415   /* Expand arguments.  */
   4416   result_args = make_tree_vec (num_result_args);
   4417   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
   4418     non_default_args_count =
   4419       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
   4420   for (in_arg = 0; in_arg < nargs; ++in_arg)
   4421     {
   4422       tree arg = TREE_VEC_ELT (args, in_arg);
   4423       if (ARGUMENT_PACK_P (arg))
   4424         {
   4425           tree packed = ARGUMENT_PACK_ARGS (arg);
   4426           int i, num_packed = TREE_VEC_LENGTH (packed);
   4427           for (i = 0; i < num_packed; ++i, ++out_arg)
   4428             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
   4429 	  if (non_default_args_count > 0)
   4430 	    non_default_args_count += num_packed - 1;
   4431         }
   4432       else
   4433         {
   4434           TREE_VEC_ELT (result_args, out_arg) = arg;
   4435           ++out_arg;
   4436         }
   4437     }
   4438   if (non_default_args_count >= 0)
   4439     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
   4440   return result_args;
   4441 }
   4442 
   4443 /* Checks if DECL shadows a template parameter.
   4444 
   4445    [temp.local]: A template-parameter shall not be redeclared within its
   4446    scope (including nested scopes).
   4447 
   4448    Emits an error and returns TRUE if the DECL shadows a parameter,
   4449    returns FALSE otherwise.  */
   4450 
   4451 bool
   4452 check_template_shadow (tree decl)
   4453 {
   4454   tree olddecl;
   4455 
   4456   /* If we're not in a template, we can't possibly shadow a template
   4457      parameter.  */
   4458   if (!current_template_parms)
   4459     return true;
   4460 
   4461   /* Figure out what we're shadowing.  */
   4462   decl = OVL_FIRST (decl);
   4463   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
   4464 
   4465   /* If there's no previous binding for this name, we're not shadowing
   4466      anything, let alone a template parameter.  */
   4467   if (!olddecl)
   4468     return true;
   4469 
   4470   /* If we're not shadowing a template parameter, we're done.  Note
   4471      that OLDDECL might be an OVERLOAD (or perhaps even an
   4472      ERROR_MARK), so we can't just blithely assume it to be a _DECL
   4473      node.  */
   4474   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
   4475     return true;
   4476 
   4477   /* We check for decl != olddecl to avoid bogus errors for using a
   4478      name inside a class.  We check TPFI to avoid duplicate errors for
   4479      inline member templates.  */
   4480   if (decl == olddecl
   4481       || (DECL_TEMPLATE_PARM_P (decl)
   4482 	  && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
   4483     return true;
   4484 
   4485   /* Don't complain about the injected class name, as we've already
   4486      complained about the class itself.  */
   4487   if (DECL_SELF_REFERENCE_P (decl))
   4488     return false;
   4489 
   4490   if (DECL_TEMPLATE_PARM_P (decl))
   4491     error ("declaration of template parameter %q+D shadows "
   4492 	   "template parameter", decl);
   4493   else
   4494     error ("declaration of %q+#D shadows template parameter", decl);
   4495   inform (DECL_SOURCE_LOCATION (olddecl),
   4496 	  "template parameter %qD declared here", olddecl);
   4497   return false;
   4498 }
   4499 
   4500 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
   4501    ORIG_LEVEL, DECL, and TYPE.  */
   4502 
   4503 static tree
   4504 build_template_parm_index (int index,
   4505 			   int level,
   4506 			   int orig_level,
   4507 			   tree decl,
   4508 			   tree type)
   4509 {
   4510   tree t = make_node (TEMPLATE_PARM_INDEX);
   4511   TEMPLATE_PARM_IDX (t) = index;
   4512   TEMPLATE_PARM_LEVEL (t) = level;
   4513   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
   4514   TEMPLATE_PARM_DECL (t) = decl;
   4515   TREE_TYPE (t) = type;
   4516   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
   4517   TREE_READONLY (t) = TREE_READONLY (decl);
   4518 
   4519   return t;
   4520 }
   4521 
   4522 struct ctp_hasher : ggc_ptr_hash<tree_node>
   4523 {
   4524   static hashval_t hash (tree t)
   4525   {
   4526     ++comparing_specializations;
   4527     tree_code code = TREE_CODE (t);
   4528     hashval_t val = iterative_hash_object (code, 0);
   4529     val = iterative_hash_object (TEMPLATE_TYPE_LEVEL (t), val);
   4530     val = iterative_hash_object (TEMPLATE_TYPE_IDX (t), val);
   4531     if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
   4532       val = iterative_hash_template_arg (CLASS_PLACEHOLDER_TEMPLATE (t), val);
   4533     if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
   4534       val = iterative_hash_template_arg (TYPE_TI_ARGS (t), val);
   4535     --comparing_specializations;
   4536     return val;
   4537   }
   4538 
   4539   static bool equal (tree t, tree u)
   4540   {
   4541     ++comparing_specializations;
   4542     bool eq = comptypes (t, u, COMPARE_STRUCTURAL);
   4543     --comparing_specializations;
   4544     return eq;
   4545   }
   4546 };
   4547 
   4548 static GTY (()) hash_table<ctp_hasher> *ctp_table;
   4549 
   4550 /* Find the canonical type parameter for the given template type
   4551    parameter.  Returns the canonical type parameter, which may be TYPE
   4552    if no such parameter existed.  */
   4553 
   4554 tree
   4555 canonical_type_parameter (tree type)
   4556 {
   4557   if (ctp_table == NULL)
   4558     ctp_table = hash_table<ctp_hasher>::create_ggc (61);
   4559 
   4560   tree& slot = *ctp_table->find_slot (type, INSERT);
   4561   if (slot == NULL_TREE)
   4562     slot = type;
   4563   return slot;
   4564 }
   4565 
   4566 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
   4567    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
   4568    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
   4569    new one is created.  */
   4570 
   4571 static tree
   4572 reduce_template_parm_level (tree index, tree type, int levels, tree args,
   4573 			    tsubst_flags_t complain)
   4574 {
   4575   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
   4576       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
   4577 	  != TEMPLATE_PARM_LEVEL (index) - levels)
   4578       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
   4579     {
   4580       tree orig_decl = TEMPLATE_PARM_DECL (index);
   4581 
   4582       tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
   4583 			      TREE_CODE (orig_decl), DECL_NAME (orig_decl),
   4584 			      type);
   4585       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
   4586       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
   4587       DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
   4588       DECL_ARTIFICIAL (decl) = 1;
   4589       SET_DECL_TEMPLATE_PARM_P (decl);
   4590 
   4591       tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
   4592 					    TEMPLATE_PARM_LEVEL (index) - levels,
   4593 					    TEMPLATE_PARM_ORIG_LEVEL (index),
   4594 					    decl, type);
   4595       TEMPLATE_PARM_DESCENDANTS (index) = tpi;
   4596       TEMPLATE_PARM_PARAMETER_PACK (tpi)
   4597 	= TEMPLATE_PARM_PARAMETER_PACK (index);
   4598 
   4599       /* Template template parameters need this.  */
   4600       tree inner = decl;
   4601       if (TREE_CODE (decl) == TEMPLATE_DECL)
   4602 	{
   4603 	  inner = build_lang_decl_loc (DECL_SOURCE_LOCATION (decl),
   4604 				       TYPE_DECL, DECL_NAME (decl), type);
   4605 	  DECL_TEMPLATE_RESULT (decl) = inner;
   4606 	  DECL_ARTIFICIAL (inner) = true;
   4607 	  tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (orig_decl),
   4608 					      args, complain);
   4609 	  DECL_TEMPLATE_PARMS (decl) = parms;
   4610 	  tree orig_inner = DECL_TEMPLATE_RESULT (orig_decl);
   4611 	  DECL_TEMPLATE_INFO (inner)
   4612 	    = build_template_info (DECL_TI_TEMPLATE (orig_inner),
   4613 				   template_parms_to_args (parms));
   4614 	}
   4615 
   4616       /* Attach the TPI to the decl.  */
   4617       if (TREE_CODE (inner) == TYPE_DECL)
   4618 	TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
   4619       else
   4620 	DECL_INITIAL (decl) = tpi;
   4621     }
   4622 
   4623   return TEMPLATE_PARM_DESCENDANTS (index);
   4624 }
   4625 
   4626 /* Process information from new template parameter PARM and append it
   4627    to the LIST being built.  This new parameter is a non-type
   4628    parameter iff IS_NON_TYPE is true. This new parameter is a
   4629    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
   4630    is in PARM_LOC.  */
   4631 
   4632 tree
   4633 process_template_parm (tree list, location_t parm_loc, tree parm,
   4634 		       bool is_non_type, bool is_parameter_pack)
   4635 {
   4636   gcc_assert (TREE_CODE (parm) == TREE_LIST);
   4637   tree prev = NULL_TREE;
   4638   int idx = 0;
   4639 
   4640   if (list)
   4641     {
   4642       prev = tree_last (list);
   4643 
   4644       tree p = TREE_VALUE (prev);
   4645       if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
   4646 	idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
   4647       else if (TREE_CODE (p) == PARM_DECL)
   4648 	idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
   4649 
   4650       ++idx;
   4651     }
   4652 
   4653   tree decl = NULL_TREE;
   4654   tree defval = TREE_PURPOSE (parm);
   4655   tree constr = TREE_TYPE (parm);
   4656 
   4657   if (is_non_type)
   4658     {
   4659       parm = TREE_VALUE (parm);
   4660 
   4661       SET_DECL_TEMPLATE_PARM_P (parm);
   4662 
   4663       if (TREE_TYPE (parm) != error_mark_node)
   4664 	{
   4665 	  /* [temp.param]
   4666 
   4667 	     The top-level cv-qualifiers on the template-parameter are
   4668 	     ignored when determining its type.  */
   4669 	  TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
   4670 	  if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
   4671 	    TREE_TYPE (parm) = error_mark_node;
   4672 	  else if (uses_parameter_packs (TREE_TYPE (parm))
   4673 		   && !is_parameter_pack
   4674 		   /* If we're in a nested template parameter list, the template
   4675 		      template parameter could be a parameter pack.  */
   4676 		   && processing_template_parmlist == 1)
   4677 	    {
   4678 	      /* This template parameter is not a parameter pack, but it
   4679 		 should be. Complain about "bare" parameter packs.  */
   4680 	      check_for_bare_parameter_packs (TREE_TYPE (parm));
   4681 
   4682 	      /* Recover by calling this a parameter pack.  */
   4683 	      is_parameter_pack = true;
   4684 	    }
   4685 	}
   4686 
   4687       /* A template parameter is not modifiable.  */
   4688       TREE_CONSTANT (parm) = 1;
   4689       TREE_READONLY (parm) = 1;
   4690       decl = build_decl (parm_loc,
   4691 			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
   4692       TREE_CONSTANT (decl) = 1;
   4693       TREE_READONLY (decl) = 1;
   4694       DECL_INITIAL (parm) = DECL_INITIAL (decl)
   4695 	= build_template_parm_index (idx, current_template_depth,
   4696 				     current_template_depth,
   4697 				     decl, TREE_TYPE (parm));
   4698 
   4699       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
   4700 	= is_parameter_pack;
   4701     }
   4702   else
   4703     {
   4704       tree t;
   4705       parm = TREE_VALUE (TREE_VALUE (parm));
   4706 
   4707       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
   4708 	{
   4709 	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
   4710 	  /* This is for distinguishing between real templates and template
   4711 	     template parameters */
   4712 	  TREE_TYPE (parm) = t;
   4713 
   4714 	  /* any_template_parm_r expects to be able to get the targs of a
   4715 	     DECL_TEMPLATE_RESULT.  */
   4716 	  tree result = DECL_TEMPLATE_RESULT (parm);
   4717 	  TREE_TYPE (result) = t;
   4718 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
   4719 	  tree tinfo = build_template_info (parm, args);
   4720 	  retrofit_lang_decl (result);
   4721 	  DECL_TEMPLATE_INFO (result) = tinfo;
   4722 
   4723 	  decl = parm;
   4724 	}
   4725       else
   4726 	{
   4727 	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
   4728 	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
   4729 	  decl = build_decl (parm_loc,
   4730 			     TYPE_DECL, parm, t);
   4731 	}
   4732 
   4733       TYPE_NAME (t) = decl;
   4734       TYPE_STUB_DECL (t) = decl;
   4735       parm = decl;
   4736       TEMPLATE_TYPE_PARM_INDEX (t)
   4737 	= build_template_parm_index (idx, current_template_depth,
   4738 				     current_template_depth,
   4739 				     decl, TREE_TYPE (parm));
   4740       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
   4741       TYPE_CANONICAL (t) = canonical_type_parameter (t);
   4742     }
   4743   DECL_ARTIFICIAL (decl) = 1;
   4744   SET_DECL_TEMPLATE_PARM_P (decl);
   4745 
   4746   if (TREE_CODE (parm) == TEMPLATE_DECL
   4747       && !uses_outer_template_parms (parm))
   4748     TEMPLATE_TEMPLATE_PARM_SIMPLE_P (TREE_TYPE (parm)) = true;
   4749 
   4750   /* Build requirements for the type/template parameter.
   4751      This must be done after SET_DECL_TEMPLATE_PARM_P or
   4752      process_template_parm could fail. */
   4753   tree reqs = finish_shorthand_constraint (parm, constr);
   4754 
   4755   decl = pushdecl (decl);
   4756   if (!is_non_type)
   4757     parm = decl;
   4758 
   4759   /* Build the parameter node linking the parameter declaration,
   4760      its default argument (if any), and its constraints (if any). */
   4761   parm = build_tree_list (defval, parm);
   4762   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
   4763 
   4764   if (prev)
   4765     TREE_CHAIN (prev) = parm;
   4766   else
   4767     list = parm;
   4768 
   4769   return list;
   4770 }
   4771 
   4772 /* The end of a template parameter list has been reached.  Process the
   4773    tree list into a parameter vector, converting each parameter into a more
   4774    useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
   4775    as PARM_DECLs.  */
   4776 
   4777 tree
   4778 end_template_parm_list (tree parms)
   4779 {
   4780   tree saved_parmlist = make_tree_vec (list_length (parms));
   4781 
   4782   /* Pop the dummy parameter level and add the real one.  We do not
   4783      morph the dummy parameter in place, as it might have been
   4784      captured by a (nested) template-template-parm.  */
   4785   current_template_parms = TREE_CHAIN (current_template_parms);
   4786 
   4787   current_template_parms
   4788     = tree_cons (size_int (current_template_depth + 1),
   4789 		 saved_parmlist, current_template_parms);
   4790 
   4791   for (unsigned ix = 0; parms; ix++)
   4792     {
   4793       tree parm = parms;
   4794       parms = TREE_CHAIN (parms);
   4795       TREE_CHAIN (parm) = NULL_TREE;
   4796 
   4797       TREE_VEC_ELT (saved_parmlist, ix) = parm;
   4798     }
   4799 
   4800   --processing_template_parmlist;
   4801 
   4802   return saved_parmlist;
   4803 }
   4804 
   4805 // Explicitly indicate the end of the template parameter list. We assume
   4806 // that the current template parameters have been constructed and/or
   4807 // managed explicitly, as when creating new template template parameters
   4808 // from a shorthand constraint.
   4809 void
   4810 end_template_parm_list ()
   4811 {
   4812   --processing_template_parmlist;
   4813 }
   4814 
   4815 /* end_template_decl is called after a template declaration is seen.  */
   4816 
   4817 void
   4818 end_template_decl (void)
   4819 {
   4820   reset_specialization ();
   4821 
   4822   if (! processing_template_decl)
   4823     return;
   4824 
   4825   /* This matches the pushlevel in begin_template_parm_list.  */
   4826   finish_scope ();
   4827 
   4828   --processing_template_decl;
   4829   current_template_parms = TREE_CHAIN (current_template_parms);
   4830 }
   4831 
   4832 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
   4833    thereof, and converts it into an argument suitable to be passed to
   4834    the type substitution functions.  Note that if the TREE_LIST contains
   4835    an error_mark node, the returned argument is error_mark_node.  */
   4836 
   4837 tree
   4838 template_parm_to_arg (tree t)
   4839 {
   4840   if (!t)
   4841     return NULL_TREE;
   4842 
   4843   if (TREE_CODE (t) == TREE_LIST)
   4844     t = TREE_VALUE (t);
   4845 
   4846   if (error_operand_p (t))
   4847     return error_mark_node;
   4848 
   4849   if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
   4850     {
   4851       if (TREE_CODE (t) == TYPE_DECL
   4852 	  || TREE_CODE (t) == TEMPLATE_DECL)
   4853 	t = TREE_TYPE (t);
   4854       else
   4855 	t = DECL_INITIAL (t);
   4856     }
   4857 
   4858   gcc_assert (TEMPLATE_PARM_P (t));
   4859 
   4860   if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
   4861       || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
   4862     {
   4863       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
   4864 	{
   4865 	  /* Turn this argument into a TYPE_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 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
   4872 
   4873 	  t = cxx_make_type (TYPE_ARGUMENT_PACK);
   4874 	  ARGUMENT_PACK_ARGS (t) = vec;
   4875 	}
   4876     }
   4877   else
   4878     {
   4879       if (TEMPLATE_PARM_PARAMETER_PACK (t))
   4880 	{
   4881 	  /* Turn this argument into a NONTYPE_ARGUMENT_PACK
   4882 	     with a single element, which expands T.  */
   4883 	  tree vec = make_tree_vec (1);
   4884 	  if (CHECKING_P)
   4885 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
   4886 
   4887 	  t = convert_from_reference (t);
   4888 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
   4889 
   4890 	  t  = make_node (NONTYPE_ARGUMENT_PACK);
   4891 	  ARGUMENT_PACK_ARGS (t) = vec;
   4892 	}
   4893       else
   4894 	t = convert_from_reference (t);
   4895     }
   4896   return t;
   4897 }
   4898 
   4899 /* If T looks like a generic template argument produced by template_parm_to_arg,
   4900    return the corresponding template parameter, otherwise return NULL_TREE.  */
   4901 
   4902 static tree
   4903 template_arg_to_parm (tree t)
   4904 {
   4905   if (t == NULL_TREE)
   4906     return NULL_TREE;
   4907 
   4908   if (ARGUMENT_PACK_P (t))
   4909     {
   4910       tree args = ARGUMENT_PACK_ARGS (t);
   4911       if (TREE_VEC_LENGTH (args) == 1
   4912 	  && PACK_EXPANSION_P (TREE_VEC_ELT (args, 0)))
   4913 	t = PACK_EXPANSION_PATTERN (TREE_VEC_ELT (args, 0));
   4914     }
   4915 
   4916   if (REFERENCE_REF_P (t))
   4917     t = TREE_OPERAND (t, 0);
   4918 
   4919   if (TEMPLATE_PARM_P (t))
   4920     return t;
   4921   else
   4922     return NULL_TREE;
   4923 }
   4924 
   4925 /* Given a single level of template parameters (a TREE_VEC), return it
   4926    as a set of template arguments.  */
   4927 
   4928 tree
   4929 template_parms_level_to_args (tree parms)
   4930 {
   4931   parms = copy_node (parms);
   4932   TREE_TYPE (parms) = NULL_TREE;
   4933   for (tree& parm : tree_vec_range (parms))
   4934     parm = template_parm_to_arg (parm);
   4935 
   4936   if (CHECKING_P)
   4937     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (parms, TREE_VEC_LENGTH (parms));
   4938 
   4939   return parms;
   4940 }
   4941 
   4942 /* Given a set of template parameters, return them as a set of template
   4943    arguments.  The template parameters are represented as a TREE_VEC, in
   4944    the form documented in cp-tree.h for template arguments.  */
   4945 
   4946 tree
   4947 template_parms_to_args (tree parms)
   4948 {
   4949   tree header;
   4950   tree args = NULL_TREE;
   4951   int length = TMPL_PARMS_DEPTH (parms);
   4952   int l = length;
   4953 
   4954   /* If there is only one level of template parameters, we do not
   4955      create a TREE_VEC of TREE_VECs.  Instead, we return a single
   4956      TREE_VEC containing the arguments.  */
   4957   if (length > 1)
   4958     args = make_tree_vec (length);
   4959 
   4960   for (header = parms; header; header = TREE_CHAIN (header))
   4961     {
   4962       tree a = template_parms_level_to_args (TREE_VALUE (header));
   4963 
   4964       if (length > 1)
   4965 	TREE_VEC_ELT (args, --l) = a;
   4966       else
   4967 	args = a;
   4968     }
   4969 
   4970   return args;
   4971 }
   4972 
   4973 /* Within the declaration of a template, return the currently active
   4974    template parameters as an argument TREE_VEC.  */
   4975 
   4976 static tree
   4977 current_template_args (void)
   4978 {
   4979   return template_parms_to_args (current_template_parms);
   4980 }
   4981 
   4982 /* Return the fully generic arguments for of TMPL, i.e. what
   4983    current_template_args would be while parsing it.  */
   4984 
   4985 tree
   4986 generic_targs_for (tree tmpl)
   4987 {
   4988   if (tmpl == NULL_TREE)
   4989     return NULL_TREE;
   4990   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
   4991       || DECL_TEMPLATE_SPECIALIZATION (tmpl))
   4992     /* DECL_TEMPLATE_RESULT doesn't have the arguments we want.  For a template
   4993        template parameter, it has no TEMPLATE_INFO; for a partial
   4994        specialization, it has the arguments for the primary template, and we
   4995        want the arguments for the partial specialization.  */;
   4996   else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
   4997     if (tree ti = get_template_info (result))
   4998       return TI_ARGS (ti);
   4999   return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
   5000 }
   5001 
   5002 /* Return the template arguments corresponding to the template parameters of
   5003    DECL's enclosing scope.  When DECL is a member of a partial specialization,
   5004    this returns the arguments for the partial specialization as opposed to those
   5005    for the primary template, which is the main difference between this function
   5006    and simply using e.g. the TYPE_TI_ARGS of DECL's DECL_CONTEXT.  */
   5007 
   5008 tree
   5009 outer_template_args (const_tree decl)
   5010 {
   5011   if (TREE_CODE (decl) == TEMPLATE_DECL)
   5012     decl = DECL_TEMPLATE_RESULT (decl);
   5013   tree ti = get_template_info (decl);
   5014   if (!ti)
   5015     return NULL_TREE;
   5016   tree args = TI_ARGS (ti);
   5017   if (!PRIMARY_TEMPLATE_P (TI_TEMPLATE (ti)))
   5018     return args;
   5019   if (TMPL_ARGS_DEPTH (args) == 1)
   5020     return NULL_TREE;
   5021   return strip_innermost_template_args (args, 1);
   5022 }
   5023 
   5024 /* Update the declared TYPE by doing any lookups which were thought to be
   5025    dependent, but are not now that we know the SCOPE of the declarator.  */
   5026 
   5027 tree
   5028 maybe_update_decl_type (tree orig_type, tree scope)
   5029 {
   5030   tree type = orig_type;
   5031 
   5032   if (type == NULL_TREE)
   5033     return type;
   5034 
   5035   if (TREE_CODE (orig_type) == TYPE_DECL)
   5036     type = TREE_TYPE (type);
   5037 
   5038   if (scope && TYPE_P (scope) && dependent_type_p (scope)
   5039       && dependent_type_p (type)
   5040       /* Don't bother building up the args in this case.  */
   5041       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
   5042     {
   5043       /* tsubst in the args corresponding to the template parameters,
   5044 	 including auto if present.  Most things will be unchanged, but
   5045 	 make_typename_type and tsubst_qualified_id will resolve
   5046 	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
   5047       tree args = current_template_args ();
   5048       tree auto_node = type_uses_auto (type);
   5049       tree pushed;
   5050       if (auto_node)
   5051 	{
   5052 	  tree auto_vec = make_tree_vec (1);
   5053 	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
   5054 	  args = add_to_template_args (args, auto_vec);
   5055 	}
   5056       pushed = push_scope (scope);
   5057       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
   5058       if (pushed)
   5059 	pop_scope (scope);
   5060     }
   5061 
   5062   if (type == error_mark_node)
   5063     return orig_type;
   5064 
   5065   if (TREE_CODE (orig_type) == TYPE_DECL)
   5066     {
   5067       if (same_type_p (type, TREE_TYPE (orig_type)))
   5068 	type = orig_type;
   5069       else
   5070 	type = TYPE_NAME (type);
   5071     }
   5072   return type;
   5073 }
   5074 
   5075 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
   5076    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
   5077    the new  template is a member template. */
   5078 
   5079 static tree
   5080 build_template_decl (tree decl, tree parms, bool member_template_p)
   5081 {
   5082   gcc_checking_assert (TREE_CODE (decl) != TEMPLATE_DECL);
   5083 
   5084   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
   5085   SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
   5086   DECL_TEMPLATE_PARMS (tmpl) = parms;
   5087   DECL_TEMPLATE_RESULT (tmpl) = decl;
   5088   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
   5089   TREE_TYPE (tmpl) = TREE_TYPE (decl);
   5090   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
   5091   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
   5092 
   5093   /* Propagate module information from the decl.  */
   5094   DECL_MODULE_EXPORT_P (tmpl) = DECL_MODULE_EXPORT_P (decl);
   5095 
   5096   return tmpl;
   5097 }
   5098 
   5099 struct template_parm_data
   5100 {
   5101   /* The level of the template parameters we are currently
   5102      processing.  */
   5103   int level;
   5104 
   5105   /* The index of the specialization argument we are currently
   5106      processing.  */
   5107   int current_arg;
   5108 
   5109   /* An array whose size is the number of template parameters.  The
   5110      elements are nonzero if the parameter has been used in any one
   5111      of the arguments processed so far.  */
   5112   int* parms;
   5113 
   5114   /* An array whose size is the number of template arguments.  The
   5115      elements are nonzero if the argument makes use of template
   5116      parameters of this level.  */
   5117   int* arg_uses_template_parms;
   5118 };
   5119 
   5120 /* Subroutine of push_template_decl used to see if each template
   5121    parameter in a partial specialization is used in the explicit
   5122    argument list.  If T is of the LEVEL given in DATA (which is
   5123    treated as a template_parm_data*), then DATA->PARMS is marked
   5124    appropriately.  */
   5125 
   5126 static int
   5127 mark_template_parm (tree t, void* data)
   5128 {
   5129   int level;
   5130   int idx;
   5131   struct template_parm_data* tpd = (struct template_parm_data*) data;
   5132 
   5133   template_parm_level_and_index (t, &level, &idx);
   5134 
   5135   if (level == tpd->level)
   5136     {
   5137       tpd->parms[idx] = 1;
   5138       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
   5139     }
   5140 
   5141   /* In C++17 the type of a non-type argument is a deduced context.  */
   5142   if (cxx_dialect >= cxx17
   5143       && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
   5144     for_each_template_parm (TREE_TYPE (t),
   5145 			    &mark_template_parm,
   5146 			    data,
   5147 			    NULL,
   5148 			    /*include_nondeduced_p=*/false);
   5149 
   5150   /* Return zero so that for_each_template_parm will continue the
   5151      traversal of the tree; we want to mark *every* template parm.  */
   5152   return 0;
   5153 }
   5154 
   5155 /* Process the partial specialization DECL.  */
   5156 
   5157 static tree
   5158 process_partial_specialization (tree decl)
   5159 {
   5160   tree type = TREE_TYPE (decl);
   5161   tree tinfo = get_template_info (decl);
   5162   tree maintmpl = TI_TEMPLATE (tinfo);
   5163   tree specargs = TI_ARGS (tinfo);
   5164   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
   5165   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
   5166   tree inner_parms;
   5167   tree inst;
   5168   int nargs = TREE_VEC_LENGTH (inner_args);
   5169   int ntparms;
   5170   int  i;
   5171   bool did_error_intro = false;
   5172   struct template_parm_data tpd;
   5173   struct template_parm_data tpd2;
   5174 
   5175   gcc_assert (current_template_parms);
   5176 
   5177   /* A concept cannot be specialized.  */
   5178   if (flag_concepts && variable_concept_p (maintmpl))
   5179     {
   5180       error ("specialization of variable concept %q#D", maintmpl);
   5181       return error_mark_node;
   5182     }
   5183 
   5184   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
   5185   ntparms = TREE_VEC_LENGTH (inner_parms);
   5186 
   5187   /* We check that each of the template parameters given in the
   5188      partial specialization is used in the argument list to the
   5189      specialization.  For example:
   5190 
   5191        template <class T> struct S;
   5192        template <class T> struct S<T*>;
   5193 
   5194      The second declaration is OK because `T*' uses the template
   5195      parameter T, whereas
   5196 
   5197        template <class T> struct S<int>;
   5198 
   5199      is no good.  Even trickier is:
   5200 
   5201        template <class T>
   5202        struct S1
   5203        {
   5204 	  template <class U>
   5205 	  struct S2;
   5206 	  template <class U>
   5207 	  struct S2<T>;
   5208        };
   5209 
   5210      The S2<T> declaration is actually invalid; it is a
   5211      full-specialization.  Of course,
   5212 
   5213 	  template <class U>
   5214 	  struct S2<T (*)(U)>;
   5215 
   5216      or some such would have been OK.  */
   5217   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
   5218   tpd.parms = XALLOCAVEC (int, ntparms);
   5219   memset (tpd.parms, 0, sizeof (int) * ntparms);
   5220 
   5221   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
   5222   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
   5223   for (i = 0; i < nargs; ++i)
   5224     {
   5225       tpd.current_arg = i;
   5226       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
   5227 			      &mark_template_parm,
   5228 			      &tpd,
   5229 			      NULL,
   5230 			      /*include_nondeduced_p=*/false);
   5231     }
   5232   for (i = 0; i < ntparms; ++i)
   5233     if (tpd.parms[i] == 0)
   5234       {
   5235 	/* One of the template parms was not used in a deduced context in the
   5236 	   specialization.  */
   5237 	if (!did_error_intro)
   5238 	  {
   5239 	    error ("template parameters not deducible in "
   5240 		   "partial specialization:");
   5241 	    did_error_intro = true;
   5242 	  }
   5243 
   5244 	inform (input_location, "        %qD",
   5245 		TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
   5246       }
   5247 
   5248   if (did_error_intro)
   5249     return error_mark_node;
   5250 
   5251   /* [temp.class.spec]
   5252 
   5253      The argument list of the specialization shall not be identical to
   5254      the implicit argument list of the primary template.  */
   5255   tree main_args
   5256     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
   5257   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
   5258       && (!flag_concepts
   5259 	  || !strictly_subsumes (current_template_constraints (), maintmpl)))
   5260     {
   5261       if (!flag_concepts)
   5262         error ("partial specialization %q+D does not specialize "
   5263 	       "any template arguments; to define the primary template, "
   5264 	       "remove the template argument list", decl);
   5265       else
   5266         error ("partial specialization %q+D does not specialize any "
   5267 	       "template arguments and is not more constrained than "
   5268 	       "the primary template; to define the primary template, "
   5269 	       "remove the template argument list", decl);
   5270       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
   5271     }
   5272 
   5273   /* A partial specialization that replaces multiple parameters of the
   5274      primary template with a pack expansion is less specialized for those
   5275      parameters.  */
   5276   if (nargs < DECL_NTPARMS (maintmpl))
   5277     {
   5278       error ("partial specialization is not more specialized than the "
   5279 	     "primary template because it replaces multiple parameters "
   5280 	     "with a pack expansion");
   5281       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
   5282       /* Avoid crash in process_partial_specialization.  */
   5283       return decl;
   5284     }
   5285 
   5286   else if (nargs > DECL_NTPARMS (maintmpl))
   5287     {
   5288       error ("too many arguments for partial specialization %qT", type);
   5289       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
   5290       /* Avoid crash below.  */
   5291       return decl;
   5292     }
   5293 
   5294   /* If we aren't in a dependent class, we can actually try deduction.  */
   5295   else if (tpd.level == 1
   5296 	   /* FIXME we should be able to handle a partial specialization of a
   5297 	      partial instantiation, but currently we can't (c++/41727).  */
   5298 	   && TMPL_ARGS_DEPTH (specargs) == 1
   5299 	   && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
   5300     {
   5301       auto_diagnostic_group d;
   5302       if (pedwarn (input_location, 0,
   5303 		   "partial specialization %qD is not more specialized than",
   5304 		   decl))
   5305 	inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
   5306 		maintmpl);
   5307     }
   5308 
   5309   /* [temp.spec.partial]
   5310 
   5311      The type of a template parameter corresponding to a specialized
   5312      non-type argument shall not be dependent on a parameter of the
   5313      specialization.
   5314 
   5315      Also, we verify that pack expansions only occur at the
   5316      end of the argument list.  */
   5317   tpd2.parms = 0;
   5318   for (i = 0; i < nargs; ++i)
   5319     {
   5320       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
   5321       tree arg = TREE_VEC_ELT (inner_args, i);
   5322       tree packed_args = NULL_TREE;
   5323       int j, len = 1;
   5324 
   5325       if (ARGUMENT_PACK_P (arg))
   5326         {
   5327           /* Extract the arguments from the argument pack. We'll be
   5328              iterating over these in the following loop.  */
   5329           packed_args = ARGUMENT_PACK_ARGS (arg);
   5330           len = TREE_VEC_LENGTH (packed_args);
   5331         }
   5332 
   5333       for (j = 0; j < len; j++)
   5334         {
   5335           if (packed_args)
   5336             /* Get the Jth argument in the parameter pack.  */
   5337             arg = TREE_VEC_ELT (packed_args, j);
   5338 
   5339           if (PACK_EXPANSION_P (arg))
   5340             {
   5341               /* Pack expansions must come at the end of the
   5342                  argument list.  */
   5343               if ((packed_args && j < len - 1)
   5344                   || (!packed_args && i < nargs - 1))
   5345                 {
   5346                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
   5347                     error ("parameter pack argument %qE must be at the "
   5348 			   "end of the template argument list", arg);
   5349                   else
   5350                     error ("parameter pack argument %qT must be at the "
   5351 			   "end of the template argument list", arg);
   5352                 }
   5353             }
   5354 
   5355           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
   5356             /* We only care about the pattern.  */
   5357             arg = PACK_EXPANSION_PATTERN (arg);
   5358 
   5359           if (/* These first two lines are the `non-type' bit.  */
   5360               !TYPE_P (arg)
   5361               && TREE_CODE (arg) != TEMPLATE_DECL
   5362               /* This next two lines are the `argument expression is not just a
   5363                  simple identifier' condition and also the `specialized
   5364                  non-type argument' bit.  */
   5365               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
   5366 	      && !((REFERENCE_REF_P (arg)
   5367 		    || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
   5368 		   && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
   5369             {
   5370 	      /* Look at the corresponding template parameter,
   5371 		 marking which template parameters its type depends
   5372 		 upon.  */
   5373 	      tree type = TREE_TYPE (parm);
   5374 
   5375 	      if (!tpd2.parms)
   5376 		{
   5377 		  /* We haven't yet initialized TPD2.  Do so now.  */
   5378 		  tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
   5379 		  /* The number of parameters here is the number in the
   5380 		     main template, which, as checked in the assertion
   5381 		     above, is NARGS.  */
   5382 		  tpd2.parms = XALLOCAVEC (int, nargs);
   5383 		  tpd2.level =
   5384 		    TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
   5385 		}
   5386 
   5387 	      /* Mark the template parameters.  But this time, we're
   5388 		 looking for the template parameters of the main
   5389 		 template, not in the specialization.  */
   5390 	      tpd2.current_arg = i;
   5391 	      tpd2.arg_uses_template_parms[i] = 0;
   5392 	      memset (tpd2.parms, 0, sizeof (int) * nargs);
   5393 	      for_each_template_parm (type,
   5394 				      &mark_template_parm,
   5395 				      &tpd2,
   5396 				      NULL,
   5397 				      /*include_nondeduced_p=*/false);
   5398 
   5399 	      if (tpd2.arg_uses_template_parms [i])
   5400 		{
   5401 		  /* The type depended on some template parameters.
   5402 		     If they are fully specialized in the
   5403 		     specialization, that's OK.  */
   5404 		  int j;
   5405 		  int count = 0;
   5406 		  for (j = 0; j < nargs; ++j)
   5407 		    if (tpd2.parms[j] != 0
   5408 			&& tpd.arg_uses_template_parms [j])
   5409 		      ++count;
   5410 		  if (count != 0)
   5411 		    error_n (input_location, count,
   5412 			     "type %qT of template argument %qE depends "
   5413 			     "on a template parameter",
   5414 			     "type %qT of template argument %qE depends "
   5415 			     "on template parameters",
   5416 			     type,
   5417 			     arg);
   5418 		}
   5419             }
   5420         }
   5421     }
   5422 
   5423   /* We should only get here once.  */
   5424   if (TREE_CODE (decl) == TYPE_DECL)
   5425     gcc_assert (!COMPLETE_TYPE_P (type));
   5426 
   5427   // Build the template decl.
   5428   tree tmpl = build_template_decl (decl, current_template_parms,
   5429 				   DECL_MEMBER_TEMPLATE_P (maintmpl));
   5430   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
   5431   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
   5432   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
   5433 
   5434   /* Give template template parms a DECL_CONTEXT of the template
   5435      for which they are a parameter.  */
   5436   for (i = 0; i < ntparms; ++i)
   5437     {
   5438       tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
   5439       if (TREE_CODE (parm) == TEMPLATE_DECL)
   5440 	DECL_CONTEXT (parm) = tmpl;
   5441     }
   5442 
   5443   if (VAR_P (decl))
   5444     {
   5445       /* We didn't register this in check_explicit_specialization so we could
   5446 	 wait until the constraints were set.  */
   5447       tree reg = register_specialization (decl, maintmpl, specargs, false, 0);
   5448       if (reg != decl)
   5449 	/* Redeclaration.  */
   5450 	return reg;
   5451     }
   5452   else
   5453     associate_classtype_constraints (type);
   5454 
   5455   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
   5456     = tree_cons (specargs, tmpl,
   5457                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
   5458   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
   5459   /* Link the DECL_TEMPLATE_RESULT back to the partial TEMPLATE_DECL.  */
   5460   gcc_checking_assert (!TI_PARTIAL_INFO (tinfo));
   5461   TI_PARTIAL_INFO (tinfo) = build_template_info (tmpl, NULL_TREE);
   5462 
   5463   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
   5464        inst = TREE_CHAIN (inst))
   5465     {
   5466       tree instance = TREE_VALUE (inst);
   5467       if (TYPE_P (instance)
   5468 	  ? (COMPLETE_TYPE_P (instance)
   5469 	     && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
   5470 	  : DECL_TEMPLATE_INSTANTIATION (instance))
   5471 	{
   5472 	  tree partial_ti = most_specialized_partial_spec (instance, tf_none,
   5473 							   /*rechecking=*/true);
   5474 	  tree inst_decl = (DECL_P (instance)
   5475 			    ? instance : TYPE_NAME (instance));
   5476 	  if (!partial_ti)
   5477 	    /* OK */;
   5478 	  else if (partial_ti == error_mark_node)
   5479 	    permerror (input_location,
   5480 		       "declaration of %qD ambiguates earlier template "
   5481 		       "instantiation for %qD", decl, inst_decl);
   5482 	  else if (TI_TEMPLATE (partial_ti) == tmpl)
   5483 	    permerror (input_location,
   5484 		       "partial specialization of %qD after instantiation "
   5485 		       "of %qD", decl, inst_decl);
   5486 	}
   5487     }
   5488 
   5489   return decl;
   5490 }
   5491 
   5492 /* PARM is a template parameter of some form; return the corresponding
   5493    TEMPLATE_PARM_INDEX.  */
   5494 
   5495 static tree
   5496 get_template_parm_index (tree parm)
   5497 {
   5498   if (TREE_CODE (parm) == PARM_DECL
   5499       || TREE_CODE (parm) == CONST_DECL)
   5500     parm = DECL_INITIAL (parm);
   5501   else if (TREE_CODE (parm) == TYPE_DECL
   5502 	   || TREE_CODE (parm) == TEMPLATE_DECL)
   5503     parm = TREE_TYPE (parm);
   5504   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
   5505       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
   5506       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
   5507     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
   5508   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
   5509   return parm;
   5510 }
   5511 
   5512 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
   5513    parameter packs used by the template parameter PARM.  */
   5514 
   5515 static void
   5516 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
   5517 {
   5518   /* A type parm can't refer to another parm.  */
   5519   if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
   5520     return;
   5521   else if (TREE_CODE (parm) == PARM_DECL)
   5522     {
   5523       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
   5524 		    ppd, ppd->visited);
   5525       return;
   5526     }
   5527 
   5528   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
   5529 
   5530   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
   5531   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
   5532     {
   5533       tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
   5534       if (template_parameter_pack_p (p))
   5535 	/* Any packs in the type are expanded by this parameter.  */;
   5536       else
   5537 	fixed_parameter_pack_p_1 (p, ppd);
   5538     }
   5539 }
   5540 
   5541 /* PARM is a template parameter pack.  Return any parameter packs used in
   5542    its type or the type of any of its template parameters.  If there are
   5543    any such packs, it will be instantiated into a fixed template parameter
   5544    list by partial instantiation rather than be fully deduced.  */
   5545 
   5546 tree
   5547 fixed_parameter_pack_p (tree parm)
   5548 {
   5549   /* This can only be true in a member template.  */
   5550   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
   5551     return NULL_TREE;
   5552   /* This can only be true for a parameter pack.  */
   5553   if (!template_parameter_pack_p (parm))
   5554     return NULL_TREE;
   5555   /* A type parm can't refer to another parm.  */
   5556   if (TREE_CODE (parm) == TYPE_DECL)
   5557     return NULL_TREE;
   5558 
   5559   tree parameter_packs = NULL_TREE;
   5560   struct find_parameter_pack_data ppd;
   5561   ppd.parameter_packs = &parameter_packs;
   5562   ppd.visited = new hash_set<tree>;
   5563   ppd.type_pack_expansion_p = false;
   5564 
   5565   fixed_parameter_pack_p_1 (parm, &ppd);
   5566 
   5567   delete ppd.visited;
   5568   return parameter_packs;
   5569 }
   5570 
   5571 /* Check that a template declaration's use of default arguments and
   5572    parameter packs is not invalid.  Here, PARMS are the template
   5573    parameters.  IS_PRIMARY is true if DECL is the thing declared by
   5574    a primary template.  IS_PARTIAL is true if DECL is a partial
   5575    specialization.
   5576 
   5577    IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
   5578    function template declaration or a friend class template
   5579    declaration.  In the function case, 1 indicates a declaration, 2
   5580    indicates a redeclaration.  When IS_FRIEND_DECL=2, no errors are
   5581    emitted for extraneous default arguments.
   5582 
   5583    Returns TRUE if there were no errors found, FALSE otherwise. */
   5584 
   5585 bool
   5586 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
   5587                          bool is_partial, int is_friend_decl)
   5588 {
   5589   const char *msg;
   5590   int last_level_to_check;
   5591   tree parm_level;
   5592   bool no_errors = true;
   5593 
   5594   /* [temp.param]
   5595 
   5596      A default template-argument shall not be specified in a
   5597      function template declaration or a function template definition, nor
   5598      in the template-parameter-list of the definition of a member of a
   5599      class template.  */
   5600 
   5601   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
   5602       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_DECL_P (decl)))
   5603     /* You can't have a function template declaration in a local
   5604        scope, nor you can you define a member of a class template in a
   5605        local scope.  */
   5606     return true;
   5607 
   5608   if ((TREE_CODE (decl) == TYPE_DECL
   5609        && TREE_TYPE (decl)
   5610        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
   5611       || (TREE_CODE (decl) == FUNCTION_DECL
   5612 	  && LAMBDA_FUNCTION_P (decl)))
   5613     /* A lambda doesn't have an explicit declaration; don't complain
   5614        about the parms of the enclosing class.  */
   5615     return true;
   5616 
   5617   if (current_class_type
   5618       && !TYPE_BEING_DEFINED (current_class_type)
   5619       && DECL_LANG_SPECIFIC (decl)
   5620       && DECL_DECLARES_FUNCTION_P (decl)
   5621       /* If this is either a friend defined in the scope of the class
   5622 	 or a member function.  */
   5623       && (DECL_FUNCTION_MEMBER_P (decl)
   5624 	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
   5625 	  : DECL_FRIEND_CONTEXT (decl)
   5626 	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
   5627 	  : false)
   5628       /* And, if it was a member function, it really was defined in
   5629 	 the scope of the class.  */
   5630       && (!DECL_FUNCTION_MEMBER_P (decl)
   5631 	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
   5632     /* We already checked these parameters when the template was
   5633        declared, so there's no need to do it again now.  This function
   5634        was defined in class scope, but we're processing its body now
   5635        that the class is complete.  */
   5636     return true;
   5637 
   5638   /* Core issue 226 (C++0x only): the following only applies to class
   5639      templates.  */
   5640   if (is_primary
   5641       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
   5642     {
   5643       /* [temp.param]
   5644 
   5645          If a template-parameter has a default template-argument, all
   5646          subsequent template-parameters shall have a default
   5647          template-argument supplied.  */
   5648       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
   5649         {
   5650           tree inner_parms = TREE_VALUE (parm_level);
   5651           int ntparms = TREE_VEC_LENGTH (inner_parms);
   5652           int seen_def_arg_p = 0;
   5653           int i;
   5654 
   5655           for (i = 0; i < ntparms; ++i)
   5656             {
   5657               tree parm = TREE_VEC_ELT (inner_parms, i);
   5658 
   5659               if (parm == error_mark_node)
   5660                 continue;
   5661 
   5662               if (TREE_PURPOSE (parm))
   5663                 seen_def_arg_p = 1;
   5664               else if (seen_def_arg_p
   5665 		       && !template_parameter_pack_p (TREE_VALUE (parm)))
   5666                 {
   5667                   error ("no default argument for %qD", TREE_VALUE (parm));
   5668                   /* For better subsequent error-recovery, we indicate that
   5669                      there should have been a default argument.  */
   5670                   TREE_PURPOSE (parm) = error_mark_node;
   5671                   no_errors = false;
   5672                 }
   5673 	      else if (!is_partial
   5674 		       && !is_friend_decl
   5675 		       /* Don't complain about an enclosing partial
   5676 			  specialization.  */
   5677 		       && parm_level == parms
   5678 		       && (TREE_CODE (decl) == TYPE_DECL || VAR_P (decl))
   5679 		       && i < ntparms - 1
   5680 		       && template_parameter_pack_p (TREE_VALUE (parm))
   5681 		       /* A fixed parameter pack will be partially
   5682 			  instantiated into a fixed length list.  */
   5683 		       && !fixed_parameter_pack_p (TREE_VALUE (parm)))
   5684 		{
   5685 		  /* A primary class template, primary variable template
   5686 		     (DR 2032), or alias template can only have one
   5687 		     parameter pack, at the end of the template
   5688 		     parameter list.  */
   5689 
   5690 		  error ("parameter pack %q+D must be at the end of the"
   5691 			 " template parameter list", TREE_VALUE (parm));
   5692 
   5693 		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
   5694 		    = error_mark_node;
   5695 		  no_errors = false;
   5696 		}
   5697             }
   5698         }
   5699     }
   5700 
   5701   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
   5702       || is_partial
   5703       || !is_primary
   5704       || is_friend_decl)
   5705     /* For an ordinary class template, default template arguments are
   5706        allowed at the innermost level, e.g.:
   5707 	 template <class T = int>
   5708 	 struct S {};
   5709        but, in a partial specialization, they're not allowed even
   5710        there, as we have in [temp.class.spec]:
   5711 
   5712 	 The template parameter list of a specialization shall not
   5713 	 contain default template argument values.
   5714 
   5715        So, for a partial specialization, or for a function template
   5716        (in C++98/C++03), we look at all of them.  */
   5717     ;
   5718   else
   5719     /* But, for a primary class template that is not a partial
   5720        specialization we look at all template parameters except the
   5721        innermost ones.  */
   5722     parms = TREE_CHAIN (parms);
   5723 
   5724   /* Figure out what error message to issue.  */
   5725   if (is_friend_decl == 2)
   5726     msg = G_("default template arguments may not be used in function template "
   5727 	     "friend re-declaration");
   5728   else if (is_friend_decl)
   5729     msg = G_("default template arguments may not be used in template "
   5730 	     "friend declarations");
   5731   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
   5732     msg = G_("default template arguments may not be used in function templates "
   5733 	     "without %<-std=c++11%> or %<-std=gnu++11%>");
   5734   else if (is_partial)
   5735     msg = G_("default template arguments may not be used in "
   5736 	     "partial specializations");
   5737   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
   5738     msg = G_("default argument for template parameter for class enclosing %qD");
   5739   else
   5740     /* Per [temp.param]/9, "A default template-argument shall not be
   5741        specified in the template-parameter-lists of the definition of
   5742        a member of a class template that appears outside of the member's
   5743        class.", thus if we aren't handling a member of a class template
   5744        there is no need to examine the parameters.  */
   5745     return true;
   5746 
   5747   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
   5748     /* If we're inside a class definition, there's no need to
   5749        examine the parameters to the class itself.  On the one
   5750        hand, they will be checked when the class is defined, and,
   5751        on the other, default arguments are valid in things like:
   5752 	 template <class T = double>
   5753 	 struct S { template <class U> void f(U); };
   5754        Here the default argument for `S' has no bearing on the
   5755        declaration of `f'.  */
   5756     last_level_to_check = template_class_depth (current_class_type) + 1;
   5757   else
   5758     /* Check everything.  */
   5759     last_level_to_check = 0;
   5760 
   5761   for (parm_level = parms;
   5762        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
   5763        parm_level = TREE_CHAIN (parm_level))
   5764     {
   5765       tree inner_parms = TREE_VALUE (parm_level);
   5766       int i;
   5767       int ntparms;
   5768 
   5769       ntparms = TREE_VEC_LENGTH (inner_parms);
   5770       for (i = 0; i < ntparms; ++i)
   5771         {
   5772           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
   5773             continue;
   5774 
   5775 	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
   5776 	    {
   5777 	      if (msg)
   5778 	        {
   5779                   no_errors = false;
   5780                   if (is_friend_decl == 2)
   5781                     return no_errors;
   5782 
   5783 		  error (msg, decl);
   5784 		  msg = 0;
   5785 	        }
   5786 
   5787 	      /* Clear out the default argument so that we are not
   5788 	         confused later.  */
   5789 	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
   5790 	    }
   5791         }
   5792 
   5793       /* At this point, if we're still interested in issuing messages,
   5794 	 they must apply to classes surrounding the object declared.  */
   5795       if (msg)
   5796 	msg = G_("default argument for template parameter for class "
   5797 		 "enclosing %qD");
   5798     }
   5799 
   5800   return no_errors;
   5801 }
   5802 
   5803 /* Worker for push_template_decl_real, called via
   5804    for_each_template_parm.  DATA is really an int, indicating the
   5805    level of the parameters we are interested in.  If T is a template
   5806    parameter of that level, return nonzero.  */
   5807 
   5808 static int
   5809 template_parm_this_level_p (tree t, void* data)
   5810 {
   5811   int this_level = *(int *)data;
   5812   int level;
   5813 
   5814   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
   5815     level = TEMPLATE_PARM_LEVEL (t);
   5816   else
   5817     level = TEMPLATE_TYPE_LEVEL (t);
   5818   return level == this_level;
   5819 }
   5820 
   5821 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
   5822    DATA is really an int, indicating the innermost outer level of parameters.
   5823    If T is a template parameter of that level or further out, return
   5824    nonzero.  */
   5825 
   5826 static int
   5827 template_parm_outer_level (tree t, void *data)
   5828 {
   5829   int this_level = *(int *)data;
   5830   int level;
   5831 
   5832   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
   5833     level = TEMPLATE_PARM_LEVEL (t);
   5834   else
   5835     level = TEMPLATE_TYPE_LEVEL (t);
   5836   return level <= this_level;
   5837 }
   5838 
   5839 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
   5840    parameters given by current_template_args, or reuses a
   5841    previously existing one, if appropriate.  Returns the DECL, or an
   5842    equivalent one, if it is replaced via a call to duplicate_decls.
   5843 
   5844    If IS_FRIEND is true, DECL is a friend declaration.  */
   5845 
   5846 tree
   5847 push_template_decl (tree decl, bool is_friend)
   5848 {
   5849   if (decl == error_mark_node || !current_template_parms)
   5850     return error_mark_node;
   5851 
   5852   /* See if this is a partial specialization.  */
   5853   bool is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
   5854 		      && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
   5855 		      && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
   5856 		     || (VAR_P (decl)
   5857 			 && DECL_LANG_SPECIFIC (decl)
   5858 			 && DECL_TEMPLATE_SPECIALIZATION (decl)
   5859 			 && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
   5860 
   5861   /* No surprising friend functions.  */
   5862   gcc_checking_assert (is_friend
   5863 		       || !(TREE_CODE (decl) == FUNCTION_DECL
   5864 			    && DECL_UNIQUE_FRIEND_P (decl)));
   5865 
   5866   tree ctx;
   5867   if (is_friend)
   5868     /* For a friend, we want the context of the friend, not
   5869        the type of which it is a friend.  */
   5870     ctx = CP_DECL_CONTEXT (decl);
   5871   else if (CP_DECL_CONTEXT (decl)
   5872 	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
   5873     /* In the case of a virtual function, we want the class in which
   5874        it is defined.  */
   5875     ctx = CP_DECL_CONTEXT (decl);
   5876   else
   5877     /* Otherwise, if we're currently defining some class, the DECL
   5878        is assumed to be a member of the class.  */
   5879     ctx = current_scope ();
   5880 
   5881   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
   5882     ctx = NULL_TREE;
   5883 
   5884   if (!DECL_CONTEXT (decl))
   5885     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
   5886 
   5887   /* See if this is a primary template.  */
   5888   bool is_primary = false;
   5889   if (is_friend && ctx
   5890       && uses_template_parms_level (ctx, current_template_depth))
   5891     /* A friend template that specifies a class context, i.e.
   5892          template <typename T> friend void A<T>::f();
   5893        is not primary.  */
   5894     ;
   5895   else if (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
   5896     /* Lambdas are not primary.  */
   5897     ;
   5898   else
   5899     is_primary = template_parm_scope_p ();
   5900 
   5901   /* True if the template is a member template, in the sense of
   5902      [temp.mem].  */
   5903   bool member_template_p = false;
   5904 
   5905   if (is_primary)
   5906     {
   5907       warning (OPT_Wtemplates, "template %qD declared", decl);
   5908 
   5909       if (DECL_CLASS_SCOPE_P (decl))
   5910 	member_template_p = true;
   5911 
   5912       if (TREE_CODE (decl) == TYPE_DECL
   5913 	  && IDENTIFIER_ANON_P (DECL_NAME (decl)))
   5914 	{
   5915 	  error ("template class without a name");
   5916 	  return error_mark_node;
   5917 	}
   5918       else if (TREE_CODE (decl) == FUNCTION_DECL)
   5919 	{
   5920 	  if (member_template_p)
   5921 	    {
   5922 	      if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
   5923 		error ("member template %qD may not have virt-specifiers", decl);
   5924 	    }
   5925 	  if (DECL_DESTRUCTOR_P (decl))
   5926 	    {
   5927 	      /* [temp.mem]
   5928 
   5929 		 A destructor shall not be a member template.  */
   5930 	      error_at (DECL_SOURCE_LOCATION (decl),
   5931 			"destructor %qD declared as member template", decl);
   5932 	      return error_mark_node;
   5933 	    }
   5934 	  if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
   5935 	      && (!prototype_p (TREE_TYPE (decl))
   5936 		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
   5937 		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
   5938 		  || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
   5939 		      == void_list_node)))
   5940 	    {
   5941 	      /* [basic.stc.dynamic.allocation]
   5942 
   5943 		 An allocation function can be a function
   5944 		 template. ... Template allocation functions shall
   5945 		 have two or more parameters.  */
   5946 	      error ("invalid template declaration of %qD", decl);
   5947 	      return error_mark_node;
   5948 	    }
   5949 	}
   5950       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
   5951 	       && CLASS_TYPE_P (TREE_TYPE (decl)))
   5952 	/* Class template.  */;
   5953       else if (TREE_CODE (decl) == TYPE_DECL
   5954 	       && TYPE_DECL_ALIAS_P (decl))
   5955 	/* alias-declaration */
   5956 	gcc_assert (!DECL_ARTIFICIAL (decl));
   5957       else if (VAR_P (decl))
   5958 	/* C++14 variable template. */;
   5959       else if (TREE_CODE (decl) == CONCEPT_DECL)
   5960 	/* C++20 concept definitions.  */;
   5961       else
   5962 	{
   5963 	  error ("template declaration of %q#D", decl);
   5964 	  return error_mark_node;
   5965 	}
   5966     }
   5967 
   5968   bool local_p = (!DECL_IMPLICIT_TYPEDEF_P (decl)
   5969 		  && ((ctx && TREE_CODE (ctx) == FUNCTION_DECL)
   5970 		      || (VAR_OR_FUNCTION_DECL_P (decl)
   5971 			  && DECL_LOCAL_DECL_P (decl))));
   5972 
   5973   /* Check to see that the rules regarding the use of default
   5974      arguments are not being violated.  We check args for a friend
   5975      functions when we know whether it's a definition, introducing
   5976      declaration or re-declaration.  */
   5977   if (!local_p && (!is_friend || TREE_CODE (decl) != FUNCTION_DECL))
   5978     check_default_tmpl_args (decl, current_template_parms,
   5979 			     is_primary, is_partial, is_friend);
   5980 
   5981   /* Ensure that there are no parameter packs in the type of this
   5982      declaration that have not been expanded.  */
   5983   if (TREE_CODE (decl) == FUNCTION_DECL)
   5984     {
   5985       /* Check each of the arguments individually to see if there are
   5986          any bare parameter packs.  */
   5987       tree type = TREE_TYPE (decl);
   5988       tree arg = DECL_ARGUMENTS (decl);
   5989       tree argtype = TYPE_ARG_TYPES (type);
   5990 
   5991       while (arg && argtype)
   5992         {
   5993           if (!DECL_PACK_P (arg)
   5994               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
   5995             {
   5996             /* This is a PARM_DECL that contains unexpanded parameter
   5997                packs. We have already complained about this in the
   5998                check_for_bare_parameter_packs call, so just replace
   5999                these types with ERROR_MARK_NODE.  */
   6000               TREE_TYPE (arg) = error_mark_node;
   6001               TREE_VALUE (argtype) = error_mark_node;
   6002             }
   6003 
   6004           arg = DECL_CHAIN (arg);
   6005           argtype = TREE_CHAIN (argtype);
   6006         }
   6007 
   6008       /* Check for bare parameter packs in the return type and the
   6009          exception specifiers.  */
   6010       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
   6011 	/* Errors were already issued, set return type to int
   6012 	   as the frontend doesn't expect error_mark_node as
   6013 	   the return type.  */
   6014 	TREE_TYPE (type) = integer_type_node;
   6015       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
   6016 	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
   6017     }
   6018   else
   6019     {
   6020       if (check_for_bare_parameter_packs (is_typedef_decl (decl)
   6021 					  ? DECL_ORIGINAL_TYPE (decl)
   6022 					  : TREE_TYPE (decl)))
   6023 	{
   6024 	  TREE_TYPE (decl) = error_mark_node;
   6025 	  return error_mark_node;
   6026 	}
   6027 
   6028       if (is_partial && VAR_P (decl)
   6029 	  && check_for_bare_parameter_packs (DECL_TI_ARGS (decl)))
   6030 	return error_mark_node;
   6031     }
   6032 
   6033   if (is_partial)
   6034     return process_partial_specialization (decl);
   6035 
   6036   tree args = current_template_args ();
   6037   tree tmpl = NULL_TREE;
   6038   bool new_template_p = false;
   6039   if (local_p)
   6040     {
   6041       /* Does not get a template head.  */
   6042       tmpl = NULL_TREE;
   6043       gcc_checking_assert (!is_primary);
   6044     }
   6045   else if (!ctx
   6046 	   || TREE_CODE (ctx) == FUNCTION_DECL
   6047 	   || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
   6048 	   || (TREE_CODE (decl) == TYPE_DECL && LAMBDA_TYPE_P (TREE_TYPE (decl)))
   6049 	   || (is_friend && !(DECL_LANG_SPECIFIC (decl)
   6050 			      && DECL_TEMPLATE_INFO (decl))))
   6051     {
   6052       if (DECL_LANG_SPECIFIC (decl)
   6053 	  && DECL_TEMPLATE_INFO (decl)
   6054 	  && DECL_TI_TEMPLATE (decl))
   6055 	tmpl = DECL_TI_TEMPLATE (decl);
   6056       /* If DECL is a TYPE_DECL for a class-template, then there won't
   6057 	 be DECL_LANG_SPECIFIC.  The information equivalent to
   6058 	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
   6059       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
   6060 	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
   6061 	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
   6062 	{
   6063 	  /* Since a template declaration already existed for this
   6064 	     class-type, we must be redeclaring it here.  Make sure
   6065 	     that the redeclaration is valid.  */
   6066 	  redeclare_class_template (TREE_TYPE (decl),
   6067 				    current_template_parms,
   6068 				    current_template_constraints ());
   6069 	  /* We don't need to create a new TEMPLATE_DECL; just use the
   6070 	     one we already had.  */
   6071 	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
   6072 	}
   6073       else
   6074 	{
   6075 	  tmpl = build_template_decl (decl, current_template_parms,
   6076 				      member_template_p);
   6077 	  new_template_p = true;
   6078 
   6079 	  if (DECL_LANG_SPECIFIC (decl)
   6080 	      && DECL_TEMPLATE_SPECIALIZATION (decl))
   6081 	    {
   6082 	      /* A specialization of a member template of a template
   6083 		 class.  */
   6084 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
   6085 	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
   6086 	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
   6087 	    }
   6088 	}
   6089     }
   6090   else
   6091     {
   6092       tree a, t, current, parms;
   6093       int i;
   6094       tree tinfo = get_template_info (decl);
   6095 
   6096       if (!tinfo)
   6097 	{
   6098 	  error ("template definition of non-template %q#D", decl);
   6099 	  return error_mark_node;
   6100 	}
   6101 
   6102       tmpl = TI_TEMPLATE (tinfo);
   6103 
   6104       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
   6105 	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
   6106 	  && DECL_TEMPLATE_SPECIALIZATION (decl)
   6107 	  && DECL_MEMBER_TEMPLATE_P (tmpl))
   6108 	{
   6109 	  /* The declaration is a specialization of a member
   6110 	     template, declared outside the class.  Therefore, the
   6111 	     innermost template arguments will be NULL, so we
   6112 	     replace them with the arguments determined by the
   6113 	     earlier call to check_explicit_specialization.  */
   6114 	  args = DECL_TI_ARGS (decl);
   6115 
   6116 	  tree new_tmpl
   6117 	    = build_template_decl (decl, current_template_parms,
   6118 				   member_template_p);
   6119 	  DECL_TI_TEMPLATE (decl) = new_tmpl;
   6120 	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
   6121 	  DECL_TEMPLATE_INFO (new_tmpl)
   6122 	    = build_template_info (tmpl, args);
   6123 
   6124 	  register_specialization (new_tmpl,
   6125 				   most_general_template (tmpl),
   6126 				   args,
   6127 				   is_friend, 0);
   6128 	  return decl;
   6129 	}
   6130 
   6131       /* Make sure the template headers we got make sense.  */
   6132 
   6133       parms = DECL_TEMPLATE_PARMS (tmpl);
   6134       i = TMPL_PARMS_DEPTH (parms);
   6135       if (TMPL_ARGS_DEPTH (args) != i)
   6136 	{
   6137 	  error ("expected %d levels of template parms for %q#D, got %d",
   6138 		 i, decl, TMPL_ARGS_DEPTH (args));
   6139 	  DECL_INTERFACE_KNOWN (decl) = 1;
   6140 	  return error_mark_node;
   6141 	}
   6142       else
   6143 	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
   6144 	  {
   6145 	    a = TMPL_ARGS_LEVEL (args, i);
   6146 	    t = INNERMOST_TEMPLATE_PARMS (parms);
   6147 
   6148 	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
   6149 	      {
   6150 		if (current == decl)
   6151 		  error ("got %d template parameters for %q#D",
   6152 			 TREE_VEC_LENGTH (a), decl);
   6153 		else
   6154 		  error ("got %d template parameters for %q#T",
   6155 			 TREE_VEC_LENGTH (a), current);
   6156 		error ("  but %d required", TREE_VEC_LENGTH (t));
   6157 		/* Avoid crash in import_export_decl.  */
   6158 		DECL_INTERFACE_KNOWN (decl) = 1;
   6159 		return error_mark_node;
   6160 	      }
   6161 
   6162 	    if (current == decl)
   6163 	      current = ctx;
   6164 	    else if (current == NULL_TREE)
   6165 	      /* Can happen in erroneous input.  */
   6166 	      break;
   6167 	    else
   6168 	      current = get_containing_scope (current);
   6169 	  }
   6170 
   6171       /* Check that the parms are used in the appropriate qualifying scopes
   6172 	 in the declarator.  */
   6173       if (!comp_template_args
   6174 	  (TI_ARGS (tinfo),
   6175 	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
   6176 	{
   6177 	  error ("template arguments to %qD do not match original "
   6178 		 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
   6179 	  if (!uses_template_parms (TI_ARGS (tinfo)))
   6180 	    inform (input_location, "use %<template<>%> for"
   6181 		    " an explicit specialization");
   6182 	  /* Avoid crash in import_export_decl.  */
   6183 	  DECL_INTERFACE_KNOWN (decl) = 1;
   6184 	  return error_mark_node;
   6185 	}
   6186 
   6187       /* Check that the constraints for each enclosing template scope are
   6188 	 consistent with the original declarations.  */
   6189       if (flag_concepts)
   6190 	{
   6191 	  tree decl_parms = DECL_TEMPLATE_PARMS (tmpl);
   6192 	  tree scope_parms = current_template_parms;
   6193 	  if (PRIMARY_TEMPLATE_P (tmpl))
   6194 	    {
   6195 	      decl_parms = TREE_CHAIN (decl_parms);
   6196 	      scope_parms = TREE_CHAIN (scope_parms);
   6197 	    }
   6198 	  while (decl_parms)
   6199 	    {
   6200 	      if (!template_requirements_equivalent_p (decl_parms, scope_parms))
   6201 		{
   6202 		  error ("redeclaration of %qD with different constraints",
   6203 			 TPARMS_PRIMARY_TEMPLATE (TREE_VALUE (decl_parms)));
   6204 		  break;
   6205 		}
   6206 	      decl_parms = TREE_CHAIN (decl_parms);
   6207 	      scope_parms = TREE_CHAIN (scope_parms);
   6208 	    }
   6209 	}
   6210     }
   6211 
   6212   gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
   6213 
   6214   if (new_template_p)
   6215     {
   6216       /* Push template declarations for global functions and types.
   6217 	 Note that we do not try to push a global template friend
   6218 	 declared in a template class; such a thing may well depend on
   6219 	 the template parameters of the class and we'll push it when
   6220 	 instantiating the befriending class.  */
   6221       if (!ctx
   6222 	  && !(is_friend && template_class_depth (current_class_type) > 0))
   6223 	{
   6224 	  tree pushed = pushdecl_namespace_level (tmpl, /*hiding=*/is_friend);
   6225 	  if (pushed == error_mark_node)
   6226 	    return error_mark_node;
   6227 
   6228 	  /* pushdecl may have found an existing template.  */
   6229 	  if (pushed != tmpl)
   6230 	    {
   6231 	      decl = DECL_TEMPLATE_RESULT (pushed);
   6232 	      tmpl = NULL_TREE;
   6233 	    }
   6234 	}
   6235       else if (is_friend)
   6236 	{
   6237 	  /* Record this decl as belonging to the current class.  It's
   6238 	     not chained onto anything else.  */
   6239 	  DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (tmpl) = true;
   6240 	  gcc_checking_assert (!DECL_CHAIN (tmpl));
   6241 	  DECL_CHAIN (tmpl) = current_scope ();
   6242 	}
   6243     }
   6244   else if (tmpl)
   6245     /* The type may have been completed, or (erroneously) changed.  */
   6246     TREE_TYPE (tmpl) = TREE_TYPE (decl);
   6247 
   6248   if (tmpl)
   6249     {
   6250       if (is_primary)
   6251 	{
   6252 	  tree parms = DECL_TEMPLATE_PARMS (tmpl);
   6253 
   6254 	  DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
   6255 
   6256 	  /* Give template template parms a DECL_CONTEXT of the template
   6257 	     for which they are a parameter.  */
   6258 	  parms = INNERMOST_TEMPLATE_PARMS (parms);
   6259 	  for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
   6260 	    {
   6261 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
   6262 	      if (TREE_CODE (parm) == TEMPLATE_DECL)
   6263 		DECL_CONTEXT (parm) = tmpl;
   6264 	    }
   6265 
   6266 	  if (TREE_CODE (decl) == TYPE_DECL
   6267 	      && TYPE_DECL_ALIAS_P (decl))
   6268 	    {
   6269 	      if (tree constr
   6270 		  = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
   6271 		{
   6272 		  /* ??? Why don't we do this here for all templates?  */
   6273 		  constr = build_constraints (constr, NULL_TREE);
   6274 		  set_constraints (decl, constr);
   6275 		}
   6276 	    }
   6277 	}
   6278 
   6279       /* The DECL_TI_ARGS of DECL contains full set of arguments
   6280 	 referring wback to its most general template.  If TMPL is a
   6281 	 specialization, ARGS may only have the innermost set of
   6282 	 arguments.  Add the missing argument levels if necessary.  */
   6283       if (DECL_TEMPLATE_INFO (tmpl))
   6284 	args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
   6285 
   6286       tree info = build_template_info (tmpl, args);
   6287 
   6288       if (DECL_IMPLICIT_TYPEDEF_P (decl))
   6289 	SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
   6290       else
   6291 	{
   6292 	  retrofit_lang_decl (decl);
   6293 	  DECL_TEMPLATE_INFO (decl) = info;
   6294 	}
   6295     }
   6296 
   6297   if (flag_implicit_templates
   6298       && !is_friend
   6299       && TREE_PUBLIC (decl)
   6300       && VAR_OR_FUNCTION_DECL_P (decl))
   6301     /* Set DECL_COMDAT on template instantiations; if we force
   6302        them to be emitted by explicit instantiation,
   6303        mark_needed will tell cgraph to do the right thing.  */
   6304     DECL_COMDAT (decl) = true;
   6305 
   6306   gcc_checking_assert (!tmpl || DECL_TEMPLATE_RESULT (tmpl) == decl);
   6307 
   6308   return decl;
   6309 }
   6310 
   6311 /* FN is an inheriting constructor that inherits from the constructor
   6312    template INHERITED; turn FN into a constructor template with a matching
   6313    template header.  */
   6314 
   6315 tree
   6316 add_inherited_template_parms (tree fn, tree inherited)
   6317 {
   6318   tree inner_parms
   6319     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
   6320   inner_parms = copy_node (inner_parms);
   6321   tree parms
   6322     = tree_cons (size_int (current_template_depth + 1),
   6323 		 inner_parms, current_template_parms);
   6324   tree tmpl = build_template_decl (fn, parms, /*member*/true);
   6325   tree args = template_parms_to_args (parms);
   6326   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
   6327   DECL_ARTIFICIAL (tmpl) = true;
   6328   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
   6329   return tmpl;
   6330 }
   6331 
   6332 /* Called when a class template TYPE is redeclared with the indicated
   6333    template PARMS, e.g.:
   6334 
   6335      template <class T> struct S;
   6336      template <class T> struct S {};  */
   6337 
   6338 bool
   6339 redeclare_class_template (tree type, tree parms, tree cons)
   6340 {
   6341   tree tmpl;
   6342   tree tmpl_parms;
   6343   int i;
   6344 
   6345   if (!TYPE_TEMPLATE_INFO (type))
   6346     {
   6347       error ("%qT is not a template type", type);
   6348       return false;
   6349     }
   6350 
   6351   tmpl = TYPE_TI_TEMPLATE (type);
   6352   if (!PRIMARY_TEMPLATE_P (tmpl))
   6353     /* The type is nested in some template class.  Nothing to worry
   6354        about here; there are no new template parameters for the nested
   6355        type.  */
   6356     return true;
   6357 
   6358   if (!parms)
   6359     {
   6360       error ("template specifiers not specified in declaration of %qD",
   6361 	     tmpl);
   6362       return false;
   6363     }
   6364 
   6365   parms = INNERMOST_TEMPLATE_PARMS (parms);
   6366   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
   6367 
   6368   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
   6369     {
   6370       error_n (input_location, TREE_VEC_LENGTH (parms),
   6371                "redeclared with %d template parameter",
   6372                "redeclared with %d template parameters",
   6373                TREE_VEC_LENGTH (parms));
   6374       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
   6375                 "previous declaration %qD used %d template parameter",
   6376                 "previous declaration %qD used %d template parameters",
   6377                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
   6378       return false;
   6379     }
   6380 
   6381   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
   6382     {
   6383       tree tmpl_parm;
   6384       tree parm;
   6385 
   6386       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
   6387           || TREE_VEC_ELT (parms, i) == error_mark_node)
   6388         continue;
   6389 
   6390       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
   6391       if (error_operand_p (tmpl_parm))
   6392 	return false;
   6393 
   6394       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
   6395 
   6396       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
   6397 	 TEMPLATE_DECL.  */
   6398       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
   6399 	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
   6400 	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
   6401 	  || (TREE_CODE (tmpl_parm) != PARM_DECL
   6402 	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
   6403 		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
   6404 	  || (TREE_CODE (tmpl_parm) == PARM_DECL
   6405 	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
   6406 		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
   6407 	{
   6408 	  auto_diagnostic_group d;
   6409 	  error ("template parameter %q+#D", tmpl_parm);
   6410 	  if (DECL_P (parm))
   6411 	    inform (DECL_SOURCE_LOCATION (parm), "redeclared here as %q#D", parm);
   6412 	  else
   6413 	    inform (input_location, "redeclared here");
   6414 	  return false;
   6415 	}
   6416 
   6417       /* The parameters can be declared to introduce different
   6418 	 constraints.  */
   6419       tree p1 = TREE_VEC_ELT (tmpl_parms, i);
   6420       tree p2 = TREE_VEC_ELT (parms, i);
   6421       if (!template_parameter_constraints_equivalent_p (p1, p2))
   6422 	{
   6423 	  auto_diagnostic_group d;
   6424 	  error ("declaration of template parameter %q+#D with different "
   6425 		 "constraints", parm);
   6426 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
   6427 		  "original declaration appeared here");
   6428 	  return false;
   6429 	}
   6430 
   6431       /* Give each template template parm in this redeclaration a
   6432 	 DECL_CONTEXT of the template for which they are a parameter.  */
   6433       if (TREE_CODE (parm) == TEMPLATE_DECL)
   6434 	{
   6435 	  gcc_checking_assert (DECL_CONTEXT (parm) == NULL_TREE
   6436 			       || DECL_CONTEXT (parm) == tmpl);
   6437 	  DECL_CONTEXT (parm) = tmpl;
   6438 	}
   6439     }
   6440 
   6441   if (!merge_default_template_args (parms, tmpl_parms, /*class_p=*/true))
   6442     return false;
   6443 
   6444   tree ci = get_constraints (tmpl);
   6445   tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
   6446   tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
   6447 
   6448   /* Two classes with different constraints declare different entities.  */
   6449   if (!cp_tree_equal (req1, req2))
   6450     {
   6451       auto_diagnostic_group d;
   6452       error_at (input_location, "redeclaration of %q#D with different "
   6453                                 "constraints", tmpl);
   6454       inform (DECL_SOURCE_LOCATION (tmpl),
   6455               "original declaration appeared here");
   6456       return false;
   6457     }
   6458 
   6459     return true;
   6460 }
   6461 
   6462 /* The actual substitution part of instantiate_non_dependent_expr,
   6463    to be used when the caller has already checked
   6464     !instantiation_dependent_uneval_expression_p (expr)
   6465    and cleared processing_template_decl.  */
   6466 
   6467 tree
   6468 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
   6469 {
   6470   return tsubst_expr (expr, /*args=*/NULL_TREE, complain, /*in_decl=*/NULL_TREE);
   6471 }
   6472 
   6473 /* Instantiate the non-dependent expression EXPR.  */
   6474 
   6475 tree
   6476 instantiate_non_dependent_expr (tree expr,
   6477 				tsubst_flags_t complain /* = tf_error */)
   6478 {
   6479   if (expr == NULL_TREE)
   6480     return NULL_TREE;
   6481 
   6482   if (processing_template_decl)
   6483     {
   6484       /* The caller should have checked this already.  */
   6485       gcc_checking_assert (!instantiation_dependent_uneval_expression_p (expr));
   6486       processing_template_decl_sentinel s;
   6487       expr = instantiate_non_dependent_expr_internal (expr, complain);
   6488     }
   6489   return expr;
   6490 }
   6491 
   6492 /* Like instantiate_non_dependent_expr, but return NULL_TREE if the
   6493    expression is dependent or non-constant.  */
   6494 
   6495 tree
   6496 instantiate_non_dependent_or_null (tree expr)
   6497 {
   6498   if (expr == NULL_TREE)
   6499     return NULL_TREE;
   6500   if (processing_template_decl)
   6501     {
   6502       if (!is_nondependent_constant_expression (expr))
   6503 	expr = NULL_TREE;
   6504       else
   6505 	{
   6506 	  processing_template_decl_sentinel s;
   6507 	  expr = instantiate_non_dependent_expr_internal (expr, tf_error);
   6508 	}
   6509     }
   6510   return expr;
   6511 }
   6512 
   6513 /* True iff T is a specialization of a variable template.  */
   6514 
   6515 bool
   6516 variable_template_specialization_p (tree t)
   6517 {
   6518   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
   6519     return false;
   6520   tree tmpl = DECL_TI_TEMPLATE (t);
   6521   return variable_template_p (tmpl);
   6522 }
   6523 
   6524 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
   6525    template declaration, or a TYPE_DECL for an alias declaration.  */
   6526 
   6527 bool
   6528 alias_type_or_template_p (tree t)
   6529 {
   6530   if (t == NULL_TREE)
   6531     return false;
   6532   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
   6533 	  || (TYPE_P (t)
   6534 	      && TYPE_NAME (t)
   6535 	      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
   6536 	  || DECL_ALIAS_TEMPLATE_P (t));
   6537 }
   6538 
   6539 /* If T is a specialization of an alias template, return it; otherwise return
   6540    NULL_TREE.  If TRANSPARENT_TYPEDEFS is true, look through other aliases.  */
   6541 
   6542 tree
   6543 alias_template_specialization_p (const_tree t,
   6544 				 bool transparent_typedefs)
   6545 {
   6546   if (!TYPE_P (t))
   6547     return NULL_TREE;
   6548 
   6549   /* It's an alias template specialization if it's an alias and its
   6550      TYPE_NAME is a specialization of a primary template.  */
   6551   if (typedef_variant_p (t))
   6552     {
   6553       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
   6554 	if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
   6555 	  return CONST_CAST_TREE (t);
   6556       if (transparent_typedefs)
   6557 	return alias_template_specialization_p (DECL_ORIGINAL_TYPE
   6558 						(TYPE_NAME (t)),
   6559 						transparent_typedefs);
   6560     }
   6561 
   6562   return NULL_TREE;
   6563 }
   6564 
   6565 /* A cache of the result of complex_alias_template_p.  */
   6566 
   6567 static GTY((deletable)) hash_map<const_tree, tree> *complex_alias_tmpl_info;
   6568 
   6569 /* Data structure for complex_alias_template_*.  */
   6570 
   6571 struct uses_all_template_parms_data
   6572 {
   6573   int level;
   6574   tree *seen;
   6575 };
   6576 
   6577 /* walk_tree callback for complex_alias_template_p.  */
   6578 
   6579 static tree
   6580 complex_alias_template_r (tree *tp, int *walk_subtrees, void *data_)
   6581 {
   6582   tree t = *tp;
   6583   auto &data = *(struct uses_all_template_parms_data*)data_;
   6584 
   6585   switch (TREE_CODE (t))
   6586     {
   6587     case TEMPLATE_TYPE_PARM:
   6588     case TEMPLATE_PARM_INDEX:
   6589     case TEMPLATE_TEMPLATE_PARM:
   6590     case BOUND_TEMPLATE_TEMPLATE_PARM:
   6591       {
   6592 	tree idx = get_template_parm_index (t);
   6593 	if (TEMPLATE_PARM_LEVEL (idx) == data.level)
   6594 	  data.seen[TEMPLATE_PARM_IDX (idx)] = boolean_true_node;
   6595       }
   6596 
   6597     default:;
   6598     }
   6599 
   6600   if (!PACK_EXPANSION_P (t))
   6601     return 0;
   6602 
   6603   /* An alias template with a pack expansion that expands a pack from the
   6604      enclosing class needs to be considered complex, to avoid confusion with
   6605      the same pack being used as an argument to the alias's own template
   6606      parameter (91966).  */
   6607   for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
   6608        pack = TREE_CHAIN (pack))
   6609     {
   6610       tree parm_pack = TREE_VALUE (pack);
   6611       if (!TEMPLATE_PARM_P (parm_pack))
   6612 	continue;
   6613       int idx, level;
   6614       template_parm_level_and_index (parm_pack, &level, &idx);
   6615       if (level < data.level)
   6616 	return t;
   6617 
   6618       /* Consider the expanded packs to be used outside the expansion...  */
   6619       data.seen[idx] = boolean_true_node;
   6620     }
   6621 
   6622   /* ...but don't walk into the pattern.  Consider PR104008:
   6623 
   6624      template <typename T, typename... Ts>
   6625      using IsOneOf = disjunction<is_same<T, Ts>...>;
   6626 
   6627      where IsOneOf seemingly uses all of its template parameters in its
   6628      expansion (and does not expand a pack from the enclosing class), so the
   6629      alias was not marked as complex.  However, if it is used like
   6630      "IsOneOf<T>", the empty pack for Ts means that T no longer appears in the
   6631      expansion.  So only Ts is considered used by the pack expansion.  */
   6632   *walk_subtrees = false;
   6633 
   6634   return 0;
   6635 }
   6636 
   6637 /* An alias template is complex from a SFINAE perspective if a template-id
   6638    using that alias can be ill-formed when the expansion is not, as with
   6639    the void_t template.
   6640 
   6641    If this predicate returns true in the ordinary case, the out parameter
   6642    SEEN_OUT is set to a TREE_VEC containing boolean_true_node at element I if
   6643    the I'th template parameter of the alias template is used in the alias.  */
   6644 
   6645 static bool
   6646 complex_alias_template_p (const_tree tmpl, tree *seen_out)
   6647 {
   6648   tmpl = most_general_template (tmpl);
   6649   if (!PRIMARY_TEMPLATE_P (tmpl))
   6650     return false;
   6651 
   6652   /* A renaming alias isn't complex.  */
   6653   if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
   6654     return false;
   6655 
   6656   /* Any other constrained alias is complex.  */
   6657   if (get_constraints (tmpl))
   6658     return true;
   6659 
   6660   /* An alias with dependent type attributes is complex.  */
   6661   if (any_dependent_type_attributes_p (DECL_ATTRIBUTES
   6662 				       (DECL_TEMPLATE_RESULT (tmpl))))
   6663     return true;
   6664 
   6665   if (!complex_alias_tmpl_info)
   6666     complex_alias_tmpl_info = hash_map<const_tree, tree>::create_ggc (13);
   6667 
   6668   if (tree *slot = complex_alias_tmpl_info->get (tmpl))
   6669     {
   6670       tree result = *slot;
   6671       if (result == boolean_false_node)
   6672 	return false;
   6673       if (result == boolean_true_node)
   6674 	return true;
   6675       gcc_assert (TREE_CODE (result) == TREE_VEC);
   6676       if (seen_out)
   6677 	*seen_out = result;
   6678       return true;
   6679     }
   6680 
   6681   struct uses_all_template_parms_data data;
   6682   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
   6683   tree parms = DECL_TEMPLATE_PARMS (tmpl);
   6684   data.level = TMPL_PARMS_DEPTH (parms);
   6685   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
   6686   tree seen = make_tree_vec (len);
   6687   data.seen = TREE_VEC_BEGIN (seen);
   6688   for (int i = 0; i < len; ++i)
   6689     data.seen[i] = boolean_false_node;
   6690 
   6691   if (cp_walk_tree_without_duplicates (&pat, complex_alias_template_r, &data))
   6692     {
   6693       complex_alias_tmpl_info->put (tmpl, boolean_true_node);
   6694       return true;
   6695     }
   6696 
   6697   for (int i = 0; i < len; ++i)
   6698     if (data.seen[i] != boolean_true_node)
   6699       {
   6700 	complex_alias_tmpl_info->put (tmpl, seen);
   6701 	if (seen_out)
   6702 	  *seen_out = seen;
   6703 	return true;
   6704       }
   6705 
   6706   complex_alias_tmpl_info->put (tmpl, boolean_false_node);
   6707   return false;
   6708 }
   6709 
   6710 /* If T is a specialization of a complex alias template with a dependent
   6711    argument for an unused template parameter, return it; otherwise return
   6712    NULL_TREE.  If T is a typedef to such a specialization, return the
   6713    specialization.  */
   6714 
   6715 tree
   6716 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
   6717 {
   6718   if (t == error_mark_node)
   6719     return NULL_TREE;
   6720   gcc_assert (TYPE_P (t));
   6721 
   6722   if (!processing_template_decl || !typedef_variant_p (t))
   6723     return NULL_TREE;
   6724 
   6725   if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
   6726     {
   6727       tree seen = NULL_TREE;
   6728       if (complex_alias_template_p (TI_TEMPLATE (tinfo), &seen))
   6729 	{
   6730 	  tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
   6731 	  if (!seen)
   6732 	    {
   6733 	      if (any_dependent_template_arguments_p (args))
   6734 		return CONST_CAST_TREE (t);
   6735 	    }
   6736 	  else
   6737 	    {
   6738 	      gcc_assert (TREE_VEC_LENGTH (args) == TREE_VEC_LENGTH (seen));
   6739 	      for (int i = 0, len = TREE_VEC_LENGTH (args); i < len; ++i)
   6740 		if (TREE_VEC_ELT (seen, i) != boolean_true_node
   6741 		    && dependent_template_arg_p (TREE_VEC_ELT (args, i)))
   6742 		  return CONST_CAST_TREE (t);
   6743 	    }
   6744 
   6745 	  return NULL_TREE;
   6746 	}
   6747     }
   6748 
   6749   if (transparent_typedefs)
   6750     {
   6751       tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
   6752       return dependent_alias_template_spec_p (utype, transparent_typedefs);
   6753     }
   6754 
   6755   return NULL_TREE;
   6756 }
   6757 
   6758 /* Return the number of innermost template parameters in TMPL.  */
   6759 
   6760 static int
   6761 num_innermost_template_parms (const_tree tmpl)
   6762 {
   6763   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
   6764   return TREE_VEC_LENGTH (parms);
   6765 }
   6766 
   6767 /* Return either TMPL or another template that it is equivalent to under DR
   6768    1286: An alias that just changes the name of a template is equivalent to
   6769    the other template.  */
   6770 
   6771 static tree
   6772 get_underlying_template (tree tmpl)
   6773 {
   6774   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
   6775   while (DECL_ALIAS_TEMPLATE_P (tmpl))
   6776     {
   6777       /* Determine if the alias is equivalent to an underlying template.  */
   6778       tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
   6779       /* The underlying type may have been ill-formed. Don't proceed.  */
   6780       if (!orig_type)
   6781 	break;
   6782       tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
   6783       if (!tinfo)
   6784 	break;
   6785 
   6786       tree underlying = TI_TEMPLATE (tinfo);
   6787       if (!PRIMARY_TEMPLATE_P (underlying)
   6788 	  || (num_innermost_template_parms (tmpl)
   6789 	      != num_innermost_template_parms (underlying)))
   6790 	break;
   6791 
   6792       /* Does the alias add cv-quals?  */
   6793       if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
   6794 	break;
   6795 
   6796       tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
   6797       if (!comp_template_args (TI_ARGS (tinfo), alias_args))
   6798 	break;
   6799 
   6800       /* Are any default template arguments equivalent?  */
   6801       tree aparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
   6802       tree uparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (underlying));
   6803       const int nparms = TREE_VEC_LENGTH (aparms);
   6804       for (int i = 0; i < nparms; ++i)
   6805 	{
   6806 	  tree adefarg = TREE_PURPOSE (TREE_VEC_ELT (aparms, i));
   6807 	  tree udefarg = TREE_PURPOSE (TREE_VEC_ELT (uparms, i));
   6808 	  if (!template_args_equal (adefarg, udefarg))
   6809 	    goto top_break;
   6810 	}
   6811 
   6812       /* If TMPL adds or changes any constraints, it isn't equivalent.  I think
   6813 	 it's appropriate to treat a less-constrained alias as equivalent.  */
   6814       if (!at_least_as_constrained (underlying, tmpl))
   6815 	break;
   6816 
   6817       /* If TMPL adds dependent type attributes, it isn't equivalent.  */
   6818       if (any_dependent_type_attributes_p (DECL_ATTRIBUTES
   6819 					   (DECL_TEMPLATE_RESULT (tmpl))))
   6820 	break;
   6821 
   6822       /* Alias is equivalent.  Strip it and repeat.  */
   6823       tmpl = underlying;
   6824     }
   6825   top_break:;
   6826 
   6827   return tmpl;
   6828 }
   6829 
   6830 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
   6831    must be a reference-to-function or a pointer-to-function type, as specified
   6832    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
   6833    and check that the resulting function has external linkage.  */
   6834 
   6835 static tree
   6836 convert_nontype_argument_function (tree type, tree expr,
   6837 				   tsubst_flags_t complain)
   6838 {
   6839   tree fns = expr;
   6840   tree fn, fn_no_ptr;
   6841   linkage_kind linkage;
   6842 
   6843   fn = instantiate_type (type, fns, tf_none);
   6844   if (fn == error_mark_node)
   6845     return error_mark_node;
   6846 
   6847   if (value_dependent_expression_p (fn))
   6848     goto accept;
   6849 
   6850   fn_no_ptr = fn;
   6851   if (REFERENCE_REF_P (fn_no_ptr))
   6852     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
   6853   fn_no_ptr = strip_fnptr_conv (fn_no_ptr);
   6854   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
   6855     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
   6856   if (BASELINK_P (fn_no_ptr))
   6857     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
   6858 
   6859   /* [temp.arg.nontype]/1
   6860 
   6861      A template-argument for a non-type, non-template template-parameter
   6862      shall be one of:
   6863      [...]
   6864      -- the address of an object or function with external [C++11: or
   6865         internal] linkage.  */
   6866 
   6867   STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
   6868   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
   6869     {
   6870       if (complain & tf_error)
   6871 	{
   6872 	  location_t loc = cp_expr_loc_or_input_loc (expr);
   6873 	  error_at (loc, "%qE is not a valid template argument for type %qT",
   6874 		    expr, type);
   6875 	  if (TYPE_PTR_P (type))
   6876 	    inform (loc, "it must be the address of a function "
   6877 		    "with external linkage");
   6878 	  else
   6879 	    inform (loc, "it must be the name of a function with "
   6880 		    "external linkage");
   6881 	}
   6882       return NULL_TREE;
   6883     }
   6884 
   6885   linkage = decl_linkage (fn_no_ptr);
   6886   if ((cxx_dialect < cxx11 && linkage != lk_external)
   6887       || (cxx_dialect < cxx17 && linkage == lk_none))
   6888     {
   6889       if (complain & tf_error)
   6890 	{
   6891 	  location_t loc = cp_expr_loc_or_input_loc (expr);
   6892 	  if (cxx_dialect >= cxx11)
   6893 	    error_at (loc, "%qE is not a valid template argument for type "
   6894 		      "%qT because %qD has no linkage",
   6895 		      expr, type, fn_no_ptr);
   6896 	  else
   6897 	    error_at (loc, "%qE is not a valid template argument for type "
   6898 		      "%qT because %qD does not have external linkage",
   6899 		      expr, type, fn_no_ptr);
   6900 	}
   6901       return NULL_TREE;
   6902     }
   6903 
   6904  accept:
   6905   if (TYPE_REF_P (type))
   6906     {
   6907       if (REFERENCE_REF_P (fn))
   6908 	fn = TREE_OPERAND (fn, 0);
   6909       else
   6910 	fn = build_address (fn);
   6911     }
   6912   if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
   6913     fn = build_nop (type, fn);
   6914 
   6915   return fn;
   6916 }
   6917 
   6918 /* Subroutine of convert_nontype_argument.
   6919    Check if EXPR of type TYPE is a valid pointer-to-member constant.
   6920    Emit an error otherwise.  */
   6921 
   6922 static bool
   6923 check_valid_ptrmem_cst_expr (tree type, tree expr,
   6924 			     tsubst_flags_t complain)
   6925 {
   6926   tree orig_expr = expr;
   6927   STRIP_NOPS (expr);
   6928   if (null_ptr_cst_p (expr))
   6929     return true;
   6930   if (TREE_CODE (expr) == PTRMEM_CST
   6931       && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
   6932 		      PTRMEM_CST_CLASS (expr)))
   6933     return true;
   6934   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
   6935     return true;
   6936   if (processing_template_decl
   6937       && TREE_CODE (expr) == ADDR_EXPR
   6938       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
   6939     return true;
   6940   if (complain & tf_error)
   6941     {
   6942       location_t loc = cp_expr_loc_or_input_loc (orig_expr);
   6943       error_at (loc, "%qE is not a valid template argument for type %qT",
   6944 		orig_expr, type);
   6945       if (TREE_CODE (expr) != PTRMEM_CST)
   6946 	inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
   6947       else
   6948 	inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
   6949     }
   6950   return false;
   6951 }
   6952 
   6953 /* Returns TRUE iff the address of OP is value-dependent.
   6954 
   6955    14.6.2.4 [temp.dep.temp]:
   6956    A non-integral non-type template-argument is dependent if its type is
   6957    dependent or it has either of the following forms
   6958      qualified-id
   6959      & qualified-id
   6960    and contains a nested-name-specifier which specifies a class-name that
   6961    names a dependent type.
   6962 
   6963    We generalize this to just say that the address of a member of a
   6964    dependent class is value-dependent; the above doesn't cover the
   6965    address of a static data member named with an unqualified-id.  */
   6966 
   6967 static bool
   6968 has_value_dependent_address (tree op)
   6969 {
   6970   STRIP_ANY_LOCATION_WRAPPER (op);
   6971 
   6972   /* We could use get_inner_reference here, but there's no need;
   6973      this is only relevant for template non-type arguments, which
   6974      can only be expressed as &id-expression.  */
   6975   if (DECL_P (op))
   6976     {
   6977       tree ctx = CP_DECL_CONTEXT (op);
   6978 
   6979       if (TYPE_P (ctx) && dependent_type_p (ctx))
   6980 	return true;
   6981 
   6982       if (VAR_P (op)
   6983 	  && TREE_STATIC (op)
   6984 	  && TREE_CODE (ctx) == FUNCTION_DECL
   6985 	  && type_dependent_expression_p (ctx))
   6986 	return true;
   6987     }
   6988 
   6989   return false;
   6990 }
   6991 
   6992 /* The next set of functions are used for providing helpful explanatory
   6993    diagnostics for failed overload resolution.  Their messages should be
   6994    indented by two spaces for consistency with the messages in
   6995    call.cc  */
   6996 
   6997 static int
   6998 unify_success (bool /*explain_p*/)
   6999 {
   7000   return 0;
   7001 }
   7002 
   7003 /* Other failure functions should call this one, to provide a single function
   7004    for setting a breakpoint on.  */
   7005 
   7006 static int
   7007 unify_invalid (bool /*explain_p*/)
   7008 {
   7009   return 1;
   7010 }
   7011 
   7012 static int
   7013 unify_parameter_deduction_failure (bool explain_p, tree parm)
   7014 {
   7015   if (explain_p)
   7016     inform (input_location,
   7017 	    "  couldn%'t deduce template parameter %qD", parm);
   7018   return unify_invalid (explain_p);
   7019 }
   7020 
   7021 static int
   7022 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
   7023 {
   7024   if (explain_p)
   7025     inform (input_location,
   7026 	    "  types %qT and %qT have incompatible cv-qualifiers",
   7027 	    parm, arg);
   7028   return unify_invalid (explain_p);
   7029 }
   7030 
   7031 static int
   7032 unify_type_mismatch (bool explain_p, tree parm, tree arg)
   7033 {
   7034   if (explain_p)
   7035     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
   7036   return unify_invalid (explain_p);
   7037 }
   7038 
   7039 static int
   7040 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
   7041 {
   7042   if (explain_p)
   7043     inform (input_location,
   7044 	    "  template parameter %qD is not a parameter pack, but "
   7045 	    "argument %qD is",
   7046 	    parm, arg);
   7047   return unify_invalid (explain_p);
   7048 }
   7049 
   7050 static int
   7051 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
   7052 {
   7053   if (explain_p)
   7054     inform (input_location,
   7055 	    "  template argument %qE does not match "
   7056 	    "pointer-to-member constant %qE",
   7057 	    arg, parm);
   7058   return unify_invalid (explain_p);
   7059 }
   7060 
   7061 static int
   7062 unify_expression_unequal (bool explain_p, tree parm, tree arg)
   7063 {
   7064   if (explain_p)
   7065     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
   7066   return unify_invalid (explain_p);
   7067 }
   7068 
   7069 static int
   7070 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
   7071 {
   7072   if (explain_p)
   7073     inform (input_location,
   7074 	    "  inconsistent parameter pack deduction with %qT and %qT",
   7075 	    old_arg, new_arg);
   7076   return unify_invalid (explain_p);
   7077 }
   7078 
   7079 static int
   7080 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
   7081 {
   7082   if (explain_p)
   7083     {
   7084       if (TYPE_P (parm))
   7085 	inform (input_location,
   7086 		"  deduced conflicting types for parameter %qT (%qT and %qT)",
   7087 		parm, first, second);
   7088       else
   7089 	inform (input_location,
   7090 		"  deduced conflicting values for non-type parameter "
   7091 		"%qE (%qE and %qE)", parm, first, second);
   7092     }
   7093   return unify_invalid (explain_p);
   7094 }
   7095 
   7096 static int
   7097 unify_vla_arg (bool explain_p, tree arg)
   7098 {
   7099   if (explain_p)
   7100     inform (input_location,
   7101 	    "  variable-sized array type %qT is not "
   7102 	    "a valid template argument",
   7103 	    arg);
   7104   return unify_invalid (explain_p);
   7105 }
   7106 
   7107 static int
   7108 unify_method_type_error (bool explain_p, tree arg)
   7109 {
   7110   if (explain_p)
   7111     inform (input_location,
   7112 	    "  member function type %qT is not a valid template argument",
   7113 	    arg);
   7114   return unify_invalid (explain_p);
   7115 }
   7116 
   7117 static int
   7118 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
   7119 {
   7120   if (explain_p)
   7121     {
   7122       if (least_p)
   7123 	inform_n (input_location, wanted,
   7124 		  "  candidate expects at least %d argument, %d provided",
   7125 		  "  candidate expects at least %d arguments, %d provided",
   7126 		  wanted, have);
   7127       else
   7128 	inform_n (input_location, wanted,
   7129 		  "  candidate expects %d argument, %d provided",
   7130 		  "  candidate expects %d arguments, %d provided",
   7131 		  wanted, have);
   7132     }
   7133   return unify_invalid (explain_p);
   7134 }
   7135 
   7136 static int
   7137 unify_too_many_arguments (bool explain_p, int have, int wanted)
   7138 {
   7139   return unify_arity (explain_p, have, wanted);
   7140 }
   7141 
   7142 static int
   7143 unify_too_few_arguments (bool explain_p, int have, int wanted,
   7144 			 bool least_p = false)
   7145 {
   7146   return unify_arity (explain_p, have, wanted, least_p);
   7147 }
   7148 
   7149 static int
   7150 unify_arg_conversion (bool explain_p, tree to_type,
   7151 		      tree from_type, tree arg)
   7152 {
   7153   if (explain_p)
   7154     inform (cp_expr_loc_or_input_loc (arg),
   7155 	    "  cannot convert %qE (type %qT) to type %qT",
   7156 	    arg, from_type, to_type);
   7157   return unify_invalid (explain_p);
   7158 }
   7159 
   7160 static int
   7161 unify_no_common_base (bool explain_p, enum template_base_result r,
   7162 		      tree parm, tree arg)
   7163 {
   7164   if (explain_p)
   7165     switch (r)
   7166       {
   7167       case tbr_ambiguous_baseclass:
   7168 	inform (input_location, "  %qT is an ambiguous base class of %qT",
   7169 		parm, arg);
   7170 	break;
   7171       default:
   7172 	inform (input_location, "  %qT is not derived from %qT", arg, parm);
   7173 	break;
   7174       }
   7175   return unify_invalid (explain_p);
   7176 }
   7177 
   7178 static int
   7179 unify_inconsistent_template_template_parameters (bool explain_p)
   7180 {
   7181   if (explain_p)
   7182     inform (input_location,
   7183 	    "  template parameters of a template template argument are "
   7184 	    "inconsistent with other deduced template arguments");
   7185   return unify_invalid (explain_p);
   7186 }
   7187 
   7188 static int
   7189 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
   7190 {
   7191   if (explain_p)
   7192     inform (input_location,
   7193 	    "  cannot deduce a template for %qT from non-template type %qT",
   7194 	    parm, arg);
   7195   return unify_invalid (explain_p);
   7196 }
   7197 
   7198 static int
   7199 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
   7200 {
   7201   if (explain_p)
   7202     inform (input_location,
   7203 	    "  template argument %qE does not match %qE", arg, parm);
   7204   return unify_invalid (explain_p);
   7205 }
   7206 
   7207 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
   7208    argument for TYPE, points to an unsuitable object.
   7209 
   7210    Also adjust the type of the index in C++20 array subobject references.  */
   7211 
   7212 static bool
   7213 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
   7214 {
   7215   switch (TREE_CODE (expr))
   7216     {
   7217     CASE_CONVERT:
   7218       return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
   7219 				       complain);
   7220 
   7221     case TARGET_EXPR:
   7222       return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
   7223 				       complain);
   7224 
   7225     case CONSTRUCTOR:
   7226       {
   7227 	for (auto &e: CONSTRUCTOR_ELTS (expr))
   7228 	  if (invalid_tparm_referent_p (TREE_TYPE (e.value), e.value, complain))
   7229 	    return true;
   7230       }
   7231       break;
   7232 
   7233     case ADDR_EXPR:
   7234       {
   7235 	tree decl = TREE_OPERAND (expr, 0);
   7236 
   7237 	if (cxx_dialect >= cxx20)
   7238 	  while (TREE_CODE (decl) == COMPONENT_REF
   7239 		 || TREE_CODE (decl) == ARRAY_REF)
   7240 	    {
   7241 	      tree &op = TREE_OPERAND (decl, 1);
   7242 	      if (TREE_CODE (decl) == ARRAY_REF
   7243 		  && TREE_CODE (op) == INTEGER_CST)
   7244 		/* Canonicalize array offsets to ptrdiff_t; how they were
   7245 		   written doesn't matter for subobject identity.  */
   7246 		op = fold_convert (ptrdiff_type_node, op);
   7247 	      decl = TREE_OPERAND (decl, 0);
   7248 	    }
   7249 
   7250 	if (!VAR_OR_FUNCTION_DECL_P (decl))
   7251 	  {
   7252 	    if (complain & tf_error)
   7253 	      error_at (cp_expr_loc_or_input_loc (expr),
   7254 			"%qE is not a valid template argument of type %qT "
   7255 			"because %qE is not a variable or function",
   7256 			expr, type, decl);
   7257 	    return true;
   7258 	  }
   7259 	else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
   7260 	  {
   7261 	    if (complain & tf_error)
   7262 	      error_at (cp_expr_loc_or_input_loc (expr),
   7263 			"%qE is not a valid template argument of type %qT "
   7264 			"in C++98 because %qD does not have external linkage",
   7265 			expr, type, decl);
   7266 	    return true;
   7267 	  }
   7268 	else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
   7269 		 && decl_linkage (decl) == lk_none)
   7270 	  {
   7271 	    if (complain & tf_error)
   7272 	      error_at (cp_expr_loc_or_input_loc (expr),
   7273 			"%qE is not a valid template argument of type %qT "
   7274 			"because %qD has no linkage", expr, type, decl);
   7275 	    return true;
   7276 	  }
   7277 	/* C++17: For a non-type template-parameter of reference or pointer
   7278 	   type, the value of the constant expression shall not refer to (or
   7279 	   for a pointer type, shall not be the address of):
   7280 	   * a subobject (4.5),
   7281 	   * a temporary object (15.2),
   7282 	   * a string literal (5.13.5),
   7283 	   * the result of a typeid expression (8.2.8), or
   7284 	   * a predefined __func__ variable (11.4.1).  */
   7285 	else if (VAR_P (decl) && DECL_ARTIFICIAL (decl)
   7286 		 && !DECL_NTTP_OBJECT_P (decl))
   7287 	  {
   7288 	    gcc_checking_assert (DECL_TINFO_P (decl) || DECL_FNAME_P (decl));
   7289 	    if (complain & tf_error)
   7290 	      error ("the address of %qD is not a valid template argument",
   7291 		     decl);
   7292 	    return true;
   7293 	  }
   7294 	else if (cxx_dialect < cxx20
   7295 		 && !(same_type_ignoring_top_level_qualifiers_p
   7296 		      (strip_array_types (TREE_TYPE (type)),
   7297 		       strip_array_types (TREE_TYPE (decl)))))
   7298 	  {
   7299 	    if (complain & tf_error)
   7300 	      error ("the address of the %qT subobject of %qD is not a "
   7301 		     "valid template argument", TREE_TYPE (type), decl);
   7302 	    return true;
   7303 	  }
   7304 	else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
   7305 	  {
   7306 	    if (complain & tf_error)
   7307 	      error ("the address of %qD is not a valid template argument "
   7308 		     "because it does not have static storage duration",
   7309 		     decl);
   7310 	    return true;
   7311 	  }
   7312       }
   7313       break;
   7314 
   7315     default:
   7316       if (!INDIRECT_TYPE_P (type))
   7317 	/* We're only concerned about pointers and references here.  */;
   7318       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
   7319 	/* Null pointer values are OK in C++11.  */;
   7320       else
   7321 	{
   7322 	  if (VAR_P (expr))
   7323 	    {
   7324 	      if (complain & tf_error)
   7325 		error ("%qD is not a valid template argument "
   7326 		       "because %qD is a variable, not the address of "
   7327 		       "a variable", expr, expr);
   7328 	      return true;
   7329 	    }
   7330 	  else
   7331 	    {
   7332 	      if (complain & tf_error)
   7333 		error ("%qE is not a valid template argument for %qT "
   7334 		       "because it is not the address of a variable",
   7335 		       expr, type);
   7336 	      return true;
   7337 	    }
   7338 	}
   7339     }
   7340   return false;
   7341 
   7342 }
   7343 
   7344 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
   7345    template argument EXPR.  */
   7346 
   7347 static tree
   7348 create_template_parm_object (tree expr, tsubst_flags_t complain)
   7349 {
   7350   tree orig = expr;
   7351   if (TREE_CODE (expr) == TARGET_EXPR)
   7352     expr = TARGET_EXPR_INITIAL (expr);
   7353 
   7354   if (!TREE_CONSTANT (expr))
   7355     {
   7356       if ((complain & tf_error)
   7357 	  && require_rvalue_constant_expression (orig))
   7358 	cxx_constant_value (orig);
   7359       return error_mark_node;
   7360     }
   7361   if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
   7362     return error_mark_node;
   7363 
   7364   /* This is no longer a compound literal.  */
   7365   gcc_assert (!TREE_HAS_CONSTRUCTOR (expr));
   7366 
   7367   return get_template_parm_object (expr, mangle_template_parm_object (expr));
   7368 }
   7369 
   7370 /* The template arguments corresponding to template parameter objects of types
   7371    that contain pointers to members.  */
   7372 
   7373 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
   7374 
   7375 /* Find or build an nttp object for (already-validated) EXPR with name
   7376    NAME.  */
   7377 
   7378 tree
   7379 get_template_parm_object (tree expr, tree name)
   7380 {
   7381   tree decl = get_global_binding (name);
   7382   if (decl)
   7383     return decl;
   7384 
   7385   tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
   7386   decl = create_temporary_var (type);
   7387   DECL_NTTP_OBJECT_P (decl) = true;
   7388   DECL_CONTEXT (decl) = NULL_TREE;
   7389   TREE_STATIC (decl) = true;
   7390   DECL_DECLARED_CONSTEXPR_P (decl) = true;
   7391   TREE_READONLY (decl) = true;
   7392   DECL_NAME (decl) = name;
   7393   SET_DECL_ASSEMBLER_NAME (decl, name);
   7394   comdat_linkage (decl);
   7395 
   7396   if (!zero_init_p (type))
   7397     {
   7398       /* If EXPR contains any PTRMEM_CST, they will get clobbered by
   7399 	 lower_var_init before we're done mangling.  So store the original
   7400 	 value elsewhere.  */
   7401       tree copy = unshare_constructor (expr);
   7402       hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
   7403     }
   7404 
   7405   pushdecl_top_level_and_finish (decl, expr);
   7406 
   7407   return decl;
   7408 }
   7409 
   7410 /* Return the actual template argument corresponding to template parameter
   7411    object VAR.  */
   7412 
   7413 tree
   7414 tparm_object_argument (tree var)
   7415 {
   7416   if (zero_init_p (TREE_TYPE (var)))
   7417     return DECL_INITIAL (var);
   7418   return *(tparm_obj_values->get (var));
   7419 }
   7420 
   7421 /* Attempt to convert the non-type template parameter EXPR to the
   7422    indicated TYPE.  If the conversion is successful, return the
   7423    converted value.  If the conversion is unsuccessful, return
   7424    NULL_TREE if we issued an error message, or error_mark_node if we
   7425    did not.  We issue error messages for out-and-out bad template
   7426    parameters, but not simply because the conversion failed, since we
   7427    might be just trying to do argument deduction.  Both TYPE and EXPR
   7428    must be non-dependent.
   7429 
   7430    The conversion follows the special rules described in
   7431    [temp.arg.nontype], and it is much more strict than an implicit
   7432    conversion.
   7433 
   7434    This function is called twice for each template argument (see
   7435    lookup_template_class for a more accurate description of this
   7436    problem). This means that we need to handle expressions which
   7437    are not valid in a C++ source, but can be created from the
   7438    first call (for instance, casts to perform conversions). These
   7439    hacks can go away after we fix the double coercion problem.  */
   7440 
   7441 static tree
   7442 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
   7443 {
   7444   tree expr_type;
   7445   location_t loc = cp_expr_loc_or_input_loc (expr);
   7446 
   7447   /* Detect immediately string literals as invalid non-type argument.
   7448      This special-case is not needed for correctness (we would easily
   7449      catch this later), but only to provide better diagnostic for this
   7450      common user mistake. As suggested by DR 100, we do not mention
   7451      linkage issues in the diagnostic as this is not the point.  */
   7452   if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
   7453     {
   7454       if (complain & tf_error)
   7455 	error ("%qE is not a valid template argument for type %qT "
   7456 	       "because string literals can never be used in this context",
   7457 	       expr, type);
   7458       return NULL_TREE;
   7459     }
   7460 
   7461   /* Add the ADDR_EXPR now for the benefit of
   7462      value_dependent_expression_p.  */
   7463   if (TYPE_PTROBV_P (type)
   7464       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
   7465     {
   7466       expr = decay_conversion (expr, complain);
   7467       if (expr == error_mark_node)
   7468 	return error_mark_node;
   7469     }
   7470 
   7471   /* If we are in a template, EXPR may be non-dependent, but still
   7472      have a syntactic, rather than semantic, form.  For example, EXPR
   7473      might be a SCOPE_REF, rather than the VAR_DECL to which the
   7474      SCOPE_REF refers.  Preserving the qualifying scope is necessary
   7475      so that access checking can be performed when the template is
   7476      instantiated -- but here we need the resolved form so that we can
   7477      convert the argument.  */
   7478   bool non_dep = false;
   7479   if (TYPE_REF_OBJ_P (type)
   7480       && has_value_dependent_address (expr))
   7481     /* If we want the address and it's value-dependent, don't fold.  */;
   7482   else if (processing_template_decl
   7483 	   && !instantiation_dependent_expression_p (expr))
   7484     non_dep = true;
   7485   if (error_operand_p (expr))
   7486     return error_mark_node;
   7487   expr_type = TREE_TYPE (expr);
   7488 
   7489   /* If the argument is non-dependent, perform any conversions in
   7490      non-dependent context as well.  */
   7491   processing_template_decl_sentinel s (non_dep);
   7492   if (non_dep)
   7493     expr = instantiate_non_dependent_expr_internal (expr, complain);
   7494 
   7495   bool val_dep_p = value_dependent_expression_p (expr);
   7496   if (val_dep_p)
   7497     expr = canonicalize_expr_argument (expr, complain);
   7498   else
   7499     STRIP_ANY_LOCATION_WRAPPER (expr);
   7500 
   7501   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
   7502      to a non-type argument of "nullptr".  */
   7503   if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
   7504     expr = fold_simple (convert (type, expr));
   7505 
   7506   /* In C++11, integral or enumeration non-type template arguments can be
   7507      arbitrary constant expressions.  Pointer and pointer to
   7508      member arguments can be general constant expressions that evaluate
   7509      to a null value, but otherwise still need to be of a specific form.  */
   7510   if (cxx_dialect >= cxx11)
   7511     {
   7512       if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
   7513 	/* A PTRMEM_CST is already constant, and a valid template
   7514 	   argument for a parameter of pointer to member type, we just want
   7515 	   to leave it in that form rather than lower it to a
   7516 	   CONSTRUCTOR.  */;
   7517       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
   7518 	       || cxx_dialect >= cxx17)
   7519 	{
   7520 	  /* C++17: A template-argument for a non-type template-parameter shall
   7521 	     be a converted constant expression (8.20) of the type of the
   7522 	     template-parameter.  */
   7523 	  expr = build_converted_constant_expr (type, expr, complain);
   7524 	  if (expr == error_mark_node)
   7525 	    /* Make sure we return NULL_TREE only if we have really issued
   7526 	       an error, as described above.  */
   7527 	    return (complain & tf_error) ? NULL_TREE : error_mark_node;
   7528 	  else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
   7529 	    {
   7530 	      IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
   7531 	      return expr;
   7532 	    }
   7533 	  expr = maybe_constant_value (expr, NULL_TREE, mce_true);
   7534 	  expr = convert_from_reference (expr);
   7535 	  /* EXPR may have become value-dependent.  */
   7536 	  val_dep_p = value_dependent_expression_p (expr);
   7537 	}
   7538       else if (TYPE_PTR_OR_PTRMEM_P (type))
   7539 	{
   7540 	  tree folded = maybe_constant_value (expr, NULL_TREE, mce_true);
   7541 	  if (TYPE_PTR_P (type) ? integer_zerop (folded)
   7542 	      : null_member_pointer_value_p (folded))
   7543 	    expr = folded;
   7544 	}
   7545     }
   7546 
   7547   if (TYPE_REF_P (type))
   7548     expr = mark_lvalue_use (expr);
   7549   else
   7550     expr = mark_rvalue_use (expr);
   7551 
   7552   /* HACK: Due to double coercion, we can get a
   7553      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
   7554      which is the tree that we built on the first call (see
   7555      below when coercing to reference to object or to reference to
   7556      function). We just strip everything and get to the arg.
   7557      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
   7558      for examples.  */
   7559   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
   7560     {
   7561       /* Check this before we strip *& to avoid redundancy.  */
   7562       if (!mark_single_function (expr, complain))
   7563 	return error_mark_node;
   7564 
   7565       tree probe_type, probe = expr;
   7566       if (REFERENCE_REF_P (probe))
   7567 	probe = TREE_OPERAND (probe, 0);
   7568       probe_type = TREE_TYPE (probe);
   7569       if (TREE_CODE (probe) == NOP_EXPR)
   7570 	{
   7571 	  /* ??? Maybe we could use convert_from_reference here, but we
   7572 	     would need to relax its constraints because the NOP_EXPR
   7573 	     could actually change the type to something more cv-qualified,
   7574 	     and this is not folded by convert_from_reference.  */
   7575 	  tree addr = TREE_OPERAND (probe, 0);
   7576 	  if (TYPE_REF_P (probe_type)
   7577 	      && TREE_CODE (addr) == ADDR_EXPR
   7578 	      && TYPE_PTR_P (TREE_TYPE (addr))
   7579 	      && (same_type_ignoring_top_level_qualifiers_p
   7580 		  (TREE_TYPE (probe_type),
   7581 		   TREE_TYPE (TREE_TYPE (addr)))))
   7582 	    {
   7583 	      expr = TREE_OPERAND (addr, 0);
   7584 	      expr_type = TREE_TYPE (probe_type);
   7585 	    }
   7586 	}
   7587     }
   7588 
   7589   /* [temp.arg.nontype]/5, bullet 1
   7590 
   7591      For a non-type template-parameter of integral or enumeration type,
   7592      integral promotions (_conv.prom_) and integral conversions
   7593      (_conv.integral_) are applied.  */
   7594   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
   7595       || SCALAR_FLOAT_TYPE_P (type))
   7596     {
   7597       if (cxx_dialect < cxx11)
   7598 	{
   7599 	  tree t = build_converted_constant_expr (type, expr, complain);
   7600 	  t = maybe_constant_value (t);
   7601 	  if (t != error_mark_node)
   7602 	    expr = t;
   7603 	}
   7604 
   7605       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
   7606 	return error_mark_node;
   7607 
   7608       /* Notice that there are constant expressions like '4 % 0' which
   7609 	 do not fold into integer constants.  */
   7610       if (!CONSTANT_CLASS_P (expr) && !val_dep_p)
   7611 	{
   7612 	  if (complain & tf_error)
   7613 	    {
   7614 	      int errs = errorcount, warns = warningcount + werrorcount;
   7615 	      if (!require_potential_constant_expression (expr))
   7616 		expr = error_mark_node;
   7617 	      else
   7618 		expr = cxx_constant_value (expr);
   7619 	      if (errorcount > errs || warningcount + werrorcount > warns)
   7620 		inform (loc, "in template argument for type %qT", type);
   7621 	      if (expr == error_mark_node)
   7622 		return NULL_TREE;
   7623 	      /* else cxx_constant_value complained but gave us
   7624 		 a real constant, so go ahead.  */
   7625 	      if (!CONSTANT_CLASS_P (expr))
   7626 		{
   7627 		  /* Some assemble time constant expressions like
   7628 		     (intptr_t)&&lab1 - (intptr_t)&&lab2 or
   7629 		     4 + (intptr_t)&&var satisfy reduced_constant_expression_p
   7630 		     as we can emit them into .rodata initializers of
   7631 		     variables, yet they can't fold into an INTEGER_CST at
   7632 		     compile time.  Refuse them here.  */
   7633 		  gcc_checking_assert (reduced_constant_expression_p (expr));
   7634 		  error_at (loc, "template argument %qE for type %qT not "
   7635 				 "a compile-time constant", expr, type);
   7636 		  return NULL_TREE;
   7637 		}
   7638 	    }
   7639 	  else
   7640 	    return NULL_TREE;
   7641 	}
   7642 
   7643       /* Avoid typedef problems.  */
   7644       if (TREE_TYPE (expr) != type)
   7645 	expr = fold_convert (type, expr);
   7646     }
   7647   /* [temp.arg.nontype]/5, bullet 2
   7648 
   7649      For a non-type template-parameter of type pointer to object,
   7650      qualification conversions (_conv.qual_) and the array-to-pointer
   7651      conversion (_conv.array_) are applied.  */
   7652   else if (TYPE_PTROBV_P (type))
   7653     {
   7654       tree decayed = expr;
   7655 
   7656       /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
   7657 	 decay_conversion or an explicit cast.  If it's a problematic cast,
   7658 	 we'll complain about it below.  */
   7659       if (TREE_CODE (expr) == NOP_EXPR)
   7660 	{
   7661 	  tree probe = expr;
   7662 	  STRIP_NOPS (probe);
   7663 	  if (TREE_CODE (probe) == ADDR_EXPR
   7664 	      && TYPE_PTR_P (TREE_TYPE (probe)))
   7665 	    {
   7666 	      expr = probe;
   7667 	      expr_type = TREE_TYPE (expr);
   7668 	    }
   7669 	}
   7670 
   7671       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
   7672 
   7673 	 A template-argument for a non-type, non-template template-parameter
   7674 	 shall be one of: [...]
   7675 
   7676 	 -- the name of a non-type template-parameter;
   7677 	 -- the address of an object or function with external linkage, [...]
   7678 	    expressed as "& id-expression" where the & is optional if the name
   7679 	    refers to a function or array, or if the corresponding
   7680 	    template-parameter is a reference.
   7681 
   7682 	Here, we do not care about functions, as they are invalid anyway
   7683 	for a parameter of type pointer-to-object.  */
   7684 
   7685       if (val_dep_p)
   7686 	/* Non-type template parameters are OK.  */
   7687 	;
   7688       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
   7689 	/* Null pointer values are OK in C++11.  */;
   7690       else if (TREE_CODE (expr) != ADDR_EXPR
   7691 	       && !INDIRECT_TYPE_P (expr_type))
   7692 	/* Other values, like integer constants, might be valid
   7693 	   non-type arguments of some other type.  */
   7694 	return error_mark_node;
   7695       else if (invalid_tparm_referent_p (type, expr, complain))
   7696 	return NULL_TREE;
   7697 
   7698       expr = decayed;
   7699 
   7700       expr = perform_qualification_conversions (type, expr);
   7701       if (expr == error_mark_node)
   7702 	return error_mark_node;
   7703     }
   7704   /* [temp.arg.nontype]/5, bullet 3
   7705 
   7706      For a non-type template-parameter of type reference to object, no
   7707      conversions apply. The type referred to by the reference may be more
   7708      cv-qualified than the (otherwise identical) type of the
   7709      template-argument. The template-parameter is bound directly to the
   7710      template-argument, which must be an lvalue.  */
   7711   else if (TYPE_REF_OBJ_P (type))
   7712     {
   7713       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
   7714 						      expr_type))
   7715 	return error_mark_node;
   7716 
   7717       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
   7718 	{
   7719 	  if (complain & tf_error)
   7720 	    error ("%qE is not a valid template argument for type %qT "
   7721 		   "because of conflicts in cv-qualification", expr, type);
   7722 	  return NULL_TREE;
   7723 	}
   7724 
   7725       if (!lvalue_p (expr))
   7726 	{
   7727 	  if (complain & tf_error)
   7728 	    error ("%qE is not a valid template argument for type %qT "
   7729 		   "because it is not an lvalue", expr, type);
   7730 	  return NULL_TREE;
   7731 	}
   7732 
   7733       /* [temp.arg.nontype]/1
   7734 
   7735 	 A template-argument for a non-type, non-template template-parameter
   7736 	 shall be one of: [...]
   7737 
   7738 	 -- the address of an object or function with external linkage.  */
   7739       if (INDIRECT_REF_P (expr)
   7740 	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
   7741 	{
   7742 	  expr = TREE_OPERAND (expr, 0);
   7743 	  if (DECL_P (expr))
   7744 	    {
   7745 	      if (complain & tf_error)
   7746 		error ("%q#D is not a valid template argument for type %qT "
   7747 		       "because a reference variable does not have a constant "
   7748 		       "address", expr, type);
   7749 	      return NULL_TREE;
   7750 	    }
   7751 	}
   7752 
   7753       if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
   7754 	/* OK, dependent reference.  We don't want to ask whether a DECL is
   7755 	   itself value-dependent, since what we want here is its address.  */;
   7756       else
   7757 	{
   7758 	  expr = build_address (expr);
   7759 
   7760 	  if (invalid_tparm_referent_p (type, expr, complain))
   7761 	    return NULL_TREE;
   7762 	}
   7763 
   7764       if (!same_type_p (type, TREE_TYPE (expr)))
   7765 	expr = build_nop (type, expr);
   7766     }
   7767   /* [temp.arg.nontype]/5, bullet 4
   7768 
   7769      For a non-type template-parameter of type pointer to function, only
   7770      the function-to-pointer conversion (_conv.func_) is applied. If the
   7771      template-argument represents a set of overloaded functions (or a
   7772      pointer to such), the matching function is selected from the set
   7773      (_over.over_).  */
   7774   else if (TYPE_PTRFN_P (type))
   7775     {
   7776       /* If the argument is a template-id, we might not have enough
   7777 	 context information to decay the pointer.  */
   7778       if (!type_unknown_p (expr_type))
   7779 	{
   7780 	  expr = decay_conversion (expr, complain);
   7781 	  if (expr == error_mark_node)
   7782 	    return error_mark_node;
   7783 	}
   7784 
   7785       if (cxx_dialect >= cxx11 && integer_zerop (expr))
   7786 	/* Null pointer values are OK in C++11.  */
   7787 	return perform_qualification_conversions (type, expr);
   7788 
   7789       expr = convert_nontype_argument_function (type, expr, complain);
   7790       if (!expr || expr == error_mark_node)
   7791 	return expr;
   7792     }
   7793   /* [temp.arg.nontype]/5, bullet 5
   7794 
   7795      For a non-type template-parameter of type reference to function, no
   7796      conversions apply. If the template-argument represents a set of
   7797      overloaded functions, the matching function is selected from the set
   7798      (_over.over_).  */
   7799   else if (TYPE_REFFN_P (type))
   7800     {
   7801       if (TREE_CODE (expr) == ADDR_EXPR)
   7802 	{
   7803 	  if (complain & tf_error)
   7804 	    {
   7805 	      error ("%qE is not a valid template argument for type %qT "
   7806 		     "because it is a pointer", expr, type);
   7807 	      inform (input_location, "try using %qE instead",
   7808 		      TREE_OPERAND (expr, 0));
   7809 	    }
   7810 	  return NULL_TREE;
   7811 	}
   7812 
   7813       expr = convert_nontype_argument_function (type, expr, complain);
   7814       if (!expr || expr == error_mark_node)
   7815 	return expr;
   7816     }
   7817   /* [temp.arg.nontype]/5, bullet 6
   7818 
   7819      For a non-type template-parameter of type pointer to member function,
   7820      no conversions apply. If the template-argument represents a set of
   7821      overloaded member functions, the matching member function is selected
   7822      from the set (_over.over_).  */
   7823   else if (TYPE_PTRMEMFUNC_P (type))
   7824     {
   7825       expr = instantiate_type (type, expr, tf_none);
   7826       if (expr == error_mark_node)
   7827 	return error_mark_node;
   7828 
   7829       /* [temp.arg.nontype] bullet 1 says the pointer to member
   7830          expression must be a pointer-to-member constant.  */
   7831       if (!val_dep_p
   7832 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
   7833 	return NULL_TREE;
   7834 
   7835       /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
   7836 	 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead.  */
   7837       if (fnptr_conv_p (type, TREE_TYPE (expr)))
   7838 	expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
   7839     }
   7840   /* [temp.arg.nontype]/5, bullet 7
   7841 
   7842      For a non-type template-parameter of type pointer to data member,
   7843      qualification conversions (_conv.qual_) are applied.  */
   7844   else if (TYPE_PTRDATAMEM_P (type))
   7845     {
   7846       /* [temp.arg.nontype] bullet 1 says the pointer to member
   7847          expression must be a pointer-to-member constant.  */
   7848       if (!val_dep_p
   7849 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
   7850 	return NULL_TREE;
   7851 
   7852       expr = perform_qualification_conversions (type, expr);
   7853       if (expr == error_mark_node)
   7854 	return expr;
   7855     }
   7856   else if (NULLPTR_TYPE_P (type))
   7857     {
   7858       if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
   7859 	{
   7860 	  if (complain & tf_error)
   7861 	    error ("%qE is not a valid template argument for type %qT "
   7862 		   "because it is of type %qT", expr, type, TREE_TYPE (expr));
   7863 	  return NULL_TREE;
   7864 	}
   7865       return expr;
   7866     }
   7867   else if (CLASS_TYPE_P (type))
   7868     {
   7869       /* Replace the argument with a reference to the corresponding template
   7870 	 parameter object.  */
   7871       if (!val_dep_p)
   7872 	expr = create_template_parm_object (expr, complain);
   7873       if (expr == error_mark_node)
   7874 	return NULL_TREE;
   7875     }
   7876   /* A template non-type parameter must be one of the above.  */
   7877   else
   7878     gcc_unreachable ();
   7879 
   7880   /* Sanity check: did we actually convert the argument to the
   7881      right type?  */
   7882   gcc_assert (same_type_ignoring_top_level_qualifiers_p
   7883 	      (type, TREE_TYPE (expr)));
   7884   return convert_from_reference (expr);
   7885 }
   7886 
   7887 /* Subroutine of coerce_template_template_parms, which returns 1 if
   7888    PARM_PARM and ARG_PARM match using the rule for the template
   7889    parameters of template template parameters. Both PARM and ARG are
   7890    template parameters; the rest of the arguments are the same as for
   7891    coerce_template_template_parms.
   7892  */
   7893 static int
   7894 coerce_template_template_parm (tree parm,
   7895                               tree arg,
   7896                               tsubst_flags_t complain,
   7897                               tree in_decl,
   7898                               tree outer_args)
   7899 {
   7900   if (arg == NULL_TREE || error_operand_p (arg)
   7901       || parm == NULL_TREE || error_operand_p (parm))
   7902     return 0;
   7903 
   7904   if (TREE_CODE (arg) != TREE_CODE (parm))
   7905     return 0;
   7906 
   7907   switch (TREE_CODE (parm))
   7908     {
   7909     case TEMPLATE_DECL:
   7910       /* We encounter instantiations of templates like
   7911 	 template <template <template <class> class> class TT>
   7912 	 class C;  */
   7913       {
   7914 	if (!coerce_template_template_parms
   7915 	    (parm, arg, complain, in_decl, outer_args))
   7916 	  return 0;
   7917       }
   7918       /* Fall through.  */
   7919 
   7920     case TYPE_DECL:
   7921       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
   7922 	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
   7923 	/* Argument is a parameter pack but parameter is not.  */
   7924 	return 0;
   7925       break;
   7926 
   7927     case PARM_DECL:
   7928       /* The tsubst call is used to handle cases such as
   7929 
   7930            template <int> class C {};
   7931 	   template <class T, template <T> class TT> class D {};
   7932 	   D<int, C> d;
   7933 
   7934 	 i.e. the parameter list of TT depends on earlier parameters.  */
   7935       if (!uses_template_parms (TREE_TYPE (arg)))
   7936 	{
   7937 	  ++processing_template_decl;
   7938 	  tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
   7939 	  --processing_template_decl;
   7940 	  if (!uses_template_parms (t)
   7941 	      && !same_type_p (t, TREE_TYPE (arg)))
   7942 	    return 0;
   7943 	}
   7944 
   7945       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
   7946 	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
   7947 	/* Argument is a parameter pack but parameter is not.  */
   7948 	return 0;
   7949 
   7950       break;
   7951 
   7952     default:
   7953       gcc_unreachable ();
   7954     }
   7955 
   7956   return 1;
   7957 }
   7958 
   7959 /* Coerce template argument list ARGLIST for use with template
   7960    template-parameter TEMPL.  */
   7961 
   7962 static tree
   7963 coerce_template_args_for_ttp (tree templ, tree arglist,
   7964 			      tsubst_flags_t complain)
   7965 {
   7966   /* Consider an example where a template template parameter declared as
   7967 
   7968      template <class T, class U = std::allocator<T> > class TT
   7969 
   7970      The template parameter level of T and U are one level larger than
   7971      of TT.  To proper process the default argument of U, say when an
   7972      instantiation `TT<int>' is seen, we need to build the full
   7973      arguments containing {int} as the innermost level.  Outer levels,
   7974      available when not appearing as default template argument, can be
   7975      obtained from the arguments of the enclosing template.
   7976 
   7977      Suppose that TT is later substituted with std::vector.  The above
   7978      instantiation is `TT<int, std::allocator<T> >' with TT at
   7979      level 1, and T at level 2, while the template arguments at level 1
   7980      becomes {std::vector} and the inner level 2 is {int}.  */
   7981 
   7982   tree outer = DECL_CONTEXT (templ);
   7983   if (outer)
   7984     outer = generic_targs_for (outer);
   7985   else if (current_template_parms)
   7986     {
   7987       /* This is an argument of the current template, so we haven't set
   7988 	 DECL_CONTEXT yet.  We can also get here when level-lowering a
   7989 	 bound ttp. */
   7990       tree relevant_template_parms;
   7991 
   7992       /* Parameter levels that are greater than the level of the given
   7993 	 template template parm are irrelevant.  */
   7994       relevant_template_parms = current_template_parms;
   7995       while (TMPL_PARMS_DEPTH (relevant_template_parms)
   7996 	     != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
   7997 	relevant_template_parms = TREE_CHAIN (relevant_template_parms);
   7998 
   7999       outer = template_parms_to_args (relevant_template_parms);
   8000     }
   8001 
   8002   if (outer)
   8003     arglist = add_to_template_args (outer, arglist);
   8004 
   8005   tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
   8006   return coerce_template_parms (parmlist, arglist, templ, complain);
   8007 }
   8008 
   8009 /* A cache of template template parameters with match-all default
   8010    arguments.  */
   8011 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
   8012 
   8013 /* T is a bound template template-parameter.  Copy its arguments into default
   8014    arguments of the template template-parameter's template parameters.  */
   8015 
   8016 static tree
   8017 add_defaults_to_ttp (tree otmpl)
   8018 {
   8019   if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
   8020     return *c;
   8021 
   8022   tree ntmpl = copy_node (otmpl);
   8023 
   8024   tree ntype = copy_node (TREE_TYPE (otmpl));
   8025   TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
   8026   TYPE_MAIN_VARIANT (ntype) = ntype;
   8027   TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
   8028   TYPE_NAME (ntype) = ntmpl;
   8029   SET_TYPE_STRUCTURAL_EQUALITY (ntype);
   8030 
   8031   tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
   8032     = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
   8033   TEMPLATE_PARM_DECL (idx) = ntmpl;
   8034   TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
   8035 
   8036   tree oparms = DECL_TEMPLATE_PARMS (otmpl);
   8037   tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
   8038   TREE_CHAIN (parms) = TREE_CHAIN (oparms);
   8039   tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
   8040   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
   8041     {
   8042       tree o = TREE_VEC_ELT (vec, i);
   8043       if (!template_parameter_pack_p (TREE_VALUE (o)))
   8044 	{
   8045 	  tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
   8046 	  TREE_PURPOSE (n) = any_targ_node;
   8047 	}
   8048     }
   8049 
   8050   tree oresult = DECL_TEMPLATE_RESULT (otmpl);
   8051   tree gen_otmpl = DECL_TI_TEMPLATE (oresult);
   8052   tree gen_ntmpl;
   8053   if (gen_otmpl == otmpl)
   8054     gen_ntmpl = ntmpl;
   8055   else
   8056     gen_ntmpl = add_defaults_to_ttp (gen_otmpl);
   8057 
   8058   tree nresult = copy_decl (oresult);
   8059   DECL_TEMPLATE_INFO (nresult)
   8060     = build_template_info (gen_ntmpl, TI_ARGS (DECL_TEMPLATE_INFO (oresult)));
   8061   DECL_TEMPLATE_RESULT (ntmpl) = nresult;
   8062 
   8063   hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
   8064   return ntmpl;
   8065 }
   8066 
   8067 /* ARG is a bound potential template template-argument, and PARGS is a list
   8068    of arguments for the corresponding template template-parameter.  Adjust
   8069    PARGS as appropriate for application to ARG's template, and if ARG is a
   8070    BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
   8071    arguments to the template template parameter.  */
   8072 
   8073 static tree
   8074 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
   8075 {
   8076   ++processing_template_decl;
   8077   tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
   8078   if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
   8079     {
   8080       /* When comparing two template template-parameters in partial ordering,
   8081 	 rewrite the one currently being used as an argument to have default
   8082 	 arguments for all parameters.  */
   8083       arg_tmpl = add_defaults_to_ttp (arg_tmpl);
   8084       pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
   8085       if (pargs != error_mark_node)
   8086 	arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
   8087 					   TYPE_TI_ARGS (arg));
   8088     }
   8089   else
   8090     {
   8091       tree aparms
   8092 	= INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
   8093       pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain);
   8094     }
   8095   --processing_template_decl;
   8096   return pargs;
   8097 }
   8098 
   8099 /* Subroutine of unify for the case when PARM is a
   8100    BOUND_TEMPLATE_TEMPLATE_PARM.  */
   8101 
   8102 static int
   8103 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
   8104 		      bool explain_p)
   8105 {
   8106   tree parmvec = TYPE_TI_ARGS (parm);
   8107   tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
   8108 
   8109   /* The template template parm might be variadic and the argument
   8110      not, so flatten both argument lists.  */
   8111   parmvec = expand_template_argument_pack (parmvec);
   8112   argvec = expand_template_argument_pack (argvec);
   8113 
   8114   if (flag_new_ttp)
   8115     {
   8116       /* In keeping with P0522R0, adjust P's template arguments
   8117 	 to apply to A's template; then flatten it again.  */
   8118       tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
   8119       nparmvec = expand_template_argument_pack (nparmvec);
   8120 
   8121       if (unify (tparms, targs, nparmvec, argvec,
   8122 		 UNIFY_ALLOW_NONE, explain_p))
   8123 	return 1;
   8124 
   8125       /* If the P0522 adjustment eliminated a pack expansion, deduce
   8126 	 empty packs.  */
   8127       if (flag_new_ttp
   8128 	  && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
   8129 	  && unify_pack_expansion (tparms, targs, parmvec, argvec,
   8130 				   DEDUCE_EXACT, /*sub*/true, explain_p))
   8131 	return 1;
   8132     }
   8133   else
   8134     {
   8135       /* Deduce arguments T, i from TT<T> or TT<i>.
   8136 	 We check each element of PARMVEC and ARGVEC individually
   8137 	 rather than the whole TREE_VEC since they can have
   8138 	 different number of elements, which is allowed under N2555.  */
   8139 
   8140       int len = TREE_VEC_LENGTH (parmvec);
   8141 
   8142       /* Check if the parameters end in a pack, making them
   8143 	 variadic.  */
   8144       int parm_variadic_p = 0;
   8145       if (len > 0
   8146 	  && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
   8147 	parm_variadic_p = 1;
   8148 
   8149       for (int i = 0; i < len - parm_variadic_p; ++i)
   8150 	/* If the template argument list of P contains a pack
   8151 	   expansion that is not the last template argument, the
   8152 	   entire template argument list is a non-deduced
   8153 	   context.  */
   8154 	if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
   8155 	  return unify_success (explain_p);
   8156 
   8157       if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
   8158 	return unify_too_few_arguments (explain_p,
   8159 					TREE_VEC_LENGTH (argvec), len);
   8160 
   8161       for (int i = 0; i < len - parm_variadic_p; ++i)
   8162 	if (unify (tparms, targs,
   8163 		   TREE_VEC_ELT (parmvec, i),
   8164 		   TREE_VEC_ELT (argvec, i),
   8165 		   UNIFY_ALLOW_NONE, explain_p))
   8166 	  return 1;
   8167 
   8168       if (parm_variadic_p
   8169 	  && unify_pack_expansion (tparms, targs,
   8170 				   parmvec, argvec,
   8171 				   DEDUCE_EXACT,
   8172 				   /*subr=*/true, explain_p))
   8173 	return 1;
   8174     }
   8175 
   8176   return 0;
   8177 }
   8178 
   8179 /* Return 1 if PARM_TMPL and ARG_TMPL match using rule for
   8180    template template parameters.
   8181 
   8182    Consider the example:
   8183      template <class T> class A;
   8184      template<template <class U> class TT> class B;
   8185 
   8186    For B<A>, PARM_TMPL is TT, while ARG_TMPL is A,
   8187    and OUTER_ARGS contains A.  */
   8188 
   8189 static int
   8190 coerce_template_template_parms (tree parm_tmpl,
   8191 				tree arg_tmpl,
   8192 				tsubst_flags_t complain,
   8193 				tree in_decl,
   8194 				tree outer_args)
   8195 {
   8196   int nparms, nargs, i;
   8197   tree parm, arg;
   8198   int variadic_p = 0;
   8199 
   8200   tree parm_parms = DECL_INNERMOST_TEMPLATE_PARMS (parm_tmpl);
   8201   tree arg_parms = DECL_INNERMOST_TEMPLATE_PARMS (arg_tmpl);
   8202   tree gen_arg_tmpl = most_general_template (arg_tmpl);
   8203   tree gen_arg_parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_arg_tmpl);
   8204 
   8205   nparms = TREE_VEC_LENGTH (parm_parms);
   8206   nargs = TREE_VEC_LENGTH (arg_parms);
   8207 
   8208   if (flag_new_ttp)
   8209     {
   8210       /* P0522R0: A template template-parameter P is at least as specialized as
   8211 	 a template template-argument A if, given the following rewrite to two
   8212 	 function templates, the function template corresponding to P is at
   8213 	 least as specialized as the function template corresponding to A
   8214 	 according to the partial ordering rules for function templates
   8215 	 ([temp.func.order]). Given an invented class template X with the
   8216 	 template parameter list of A (including default arguments):
   8217 
   8218 	 * Each of the two function templates has the same template parameters,
   8219 	 respectively, as P or A.
   8220 
   8221 	 * Each function template has a single function parameter whose type is
   8222 	 a specialization of X with template arguments corresponding to the
   8223 	 template parameters from the respective function template where, for
   8224 	 each template parameter PP in the template parameter list of the
   8225 	 function template, a corresponding template argument AA is formed. If
   8226 	 PP declares a parameter pack, then AA is the pack expansion
   8227 	 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
   8228 
   8229 	 If the rewrite produces an invalid type, then P is not at least as
   8230 	 specialized as A.  */
   8231 
   8232       /* So coerce P's args to apply to A's parms, and then deduce between A's
   8233 	 args and the converted args.  If that succeeds, A is at least as
   8234 	 specialized as P, so they match.*/
   8235       processing_template_decl_sentinel ptds (/*reset*/false);
   8236       ++processing_template_decl;
   8237 
   8238       tree pargs = template_parms_level_to_args (parm_parms);
   8239 
   8240       /* PARM and ARG might be at different template depths, and we want to
   8241 	 pass the right additional levels of args when coercing PARGS to
   8242 	 ARG_PARMS in case we need to do any substitution into non-type
   8243 	 template parameter types.
   8244 
   8245 	 OUTER_ARGS are not the right outer levels in this case, as they are
   8246 	 the args we're building up for PARM, and for the coercion we want the
   8247 	 args for ARG.  If DECL_CONTEXT isn't set for a template template
   8248 	 parameter, we can assume that it's in the current scope.  */
   8249       tree ctx = DECL_CONTEXT (arg_tmpl);
   8250       if (!ctx && DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
   8251 	ctx = current_scope ();
   8252       tree scope_args = NULL_TREE;
   8253       if (tree tinfo = get_template_info (ctx))
   8254 	scope_args = TI_ARGS (tinfo);
   8255       if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
   8256 	{
   8257 	  int level = TEMPLATE_TYPE_LEVEL (TREE_TYPE (gen_arg_tmpl));
   8258 	  int scope_depth = TMPL_ARGS_DEPTH (scope_args);
   8259 	  tree full_pargs = make_tree_vec (level + 1);
   8260 
   8261 	/* Only use as many levels from the scope as needed
   8262 	   (excluding the level of ARG).  */
   8263 	  for (int i = 0; i < level - 1; ++i)
   8264 	    if (i < scope_depth)
   8265 	      TREE_VEC_ELT (full_pargs, i) = TMPL_ARGS_LEVEL (scope_args, i + 1);
   8266 	    else
   8267 	      TREE_VEC_ELT (full_pargs, i) = make_tree_vec (0);
   8268 
   8269 	  /* Add the arguments that appear at the levels of ARG.  */
   8270 	  tree adjacent = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (arg_tmpl));
   8271 	  adjacent = TMPL_ARGS_LEVEL (adjacent, TMPL_ARGS_DEPTH (adjacent) - 1);
   8272 	  TREE_VEC_ELT (full_pargs, level - 1) = adjacent;
   8273 
   8274 	  TREE_VEC_ELT (full_pargs, level) = pargs;
   8275 	  pargs = full_pargs;
   8276 	}
   8277       else
   8278 	pargs = add_to_template_args (scope_args, pargs);
   8279 
   8280       pargs = coerce_template_parms (gen_arg_parms, pargs,
   8281 				     NULL_TREE, tf_none);
   8282       if (pargs != error_mark_node)
   8283 	{
   8284 	  tree targs = make_tree_vec (nargs);
   8285 	  tree aargs = template_parms_level_to_args (arg_parms);
   8286 	  if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
   8287 		      /*explain*/false))
   8288 	    return 1;
   8289 	}
   8290     }
   8291 
   8292   /* Determine whether we have a parameter pack at the end of the
   8293      template template parameter's template parameter list.  */
   8294   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
   8295     {
   8296       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
   8297 
   8298       if (error_operand_p (parm))
   8299 	return 0;
   8300 
   8301       switch (TREE_CODE (parm))
   8302         {
   8303         case TEMPLATE_DECL:
   8304         case TYPE_DECL:
   8305           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
   8306             variadic_p = 1;
   8307           break;
   8308 
   8309         case PARM_DECL:
   8310           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
   8311             variadic_p = 1;
   8312           break;
   8313 
   8314         default:
   8315           gcc_unreachable ();
   8316         }
   8317     }
   8318 
   8319   if (nargs != nparms
   8320       && !(variadic_p && nargs >= nparms - 1))
   8321     return 0;
   8322 
   8323   /* Check all of the template parameters except the parameter pack at
   8324      the end (if any).  */
   8325   for (i = 0; i < nparms - variadic_p; ++i)
   8326     {
   8327       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
   8328           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
   8329         continue;
   8330 
   8331       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
   8332       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
   8333 
   8334       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
   8335                                           outer_args))
   8336 	return 0;
   8337 
   8338     }
   8339 
   8340   if (variadic_p)
   8341     {
   8342       /* Check each of the template parameters in the template
   8343 	 argument against the template parameter pack at the end of
   8344 	 the template template parameter.  */
   8345       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
   8346 	return 0;
   8347 
   8348       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
   8349 
   8350       for (; i < nargs; ++i)
   8351         {
   8352           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
   8353             continue;
   8354 
   8355           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
   8356 
   8357           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
   8358                                               outer_args))
   8359             return 0;
   8360         }
   8361     }
   8362 
   8363   return 1;
   8364 }
   8365 
   8366 /* Verifies that the deduced template arguments (in TARGS) for the
   8367    template template parameters (in TPARMS) represent valid bindings,
   8368    by comparing the template parameter list of each template argument
   8369    to the template parameter list of its corresponding template
   8370    template parameter, in accordance with DR150. This
   8371    routine can only be called after all template arguments have been
   8372    deduced. It will return TRUE if all of the template template
   8373    parameter bindings are okay, FALSE otherwise.  */
   8374 bool
   8375 template_template_parm_bindings_ok_p (tree tparms, tree targs)
   8376 {
   8377   int i, ntparms = TREE_VEC_LENGTH (tparms);
   8378   bool ret = true;
   8379 
   8380   /* We're dealing with template parms in this process.  */
   8381   ++processing_template_decl;
   8382 
   8383   targs = INNERMOST_TEMPLATE_ARGS (targs);
   8384 
   8385   for (i = 0; i < ntparms; ++i)
   8386     {
   8387       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
   8388       tree targ = TREE_VEC_ELT (targs, i);
   8389 
   8390       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
   8391 	{
   8392 	  tree packed_args = NULL_TREE;
   8393 	  int idx, len = 1;
   8394 
   8395 	  if (ARGUMENT_PACK_P (targ))
   8396 	    {
   8397 	      /* Look inside the argument pack.  */
   8398 	      packed_args = ARGUMENT_PACK_ARGS (targ);
   8399 	      len = TREE_VEC_LENGTH (packed_args);
   8400 	    }
   8401 
   8402 	  for (idx = 0; idx < len; ++idx)
   8403 	    {
   8404 	      if (packed_args)
   8405 		/* Extract the next argument from the argument
   8406 		   pack.  */
   8407 		targ = TREE_VEC_ELT (packed_args, idx);
   8408 
   8409 	      if (PACK_EXPANSION_P (targ))
   8410 		/* Look at the pattern of the pack expansion.  */
   8411 		targ = PACK_EXPANSION_PATTERN (targ);
   8412 
   8413 	      /* Extract the template parameters from the template
   8414 		 argument.  */
   8415 	      if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
   8416 		targ = TYPE_NAME (targ);
   8417 
   8418 	      /* Verify that we can coerce the template template
   8419 		 parameters from the template argument to the template
   8420 		 parameter.  This requires an exact match.  */
   8421 	      if (TREE_CODE (targ) == TEMPLATE_DECL
   8422 		  && !coerce_template_template_parms
   8423 		       (tparm,
   8424 			targ,
   8425 			tf_none,
   8426 			tparm,
   8427 			targs))
   8428 		{
   8429 		  ret = false;
   8430 		  goto out;
   8431 		}
   8432 	    }
   8433 	}
   8434     }
   8435 
   8436  out:
   8437 
   8438   --processing_template_decl;
   8439   return ret;
   8440 }
   8441 
   8442 /* Since type attributes aren't mangled, we need to strip them from
   8443    template type arguments.  */
   8444 
   8445 tree
   8446 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
   8447 {
   8448   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
   8449     return arg;
   8450   bool removed_attributes = false;
   8451   tree canon = strip_typedefs (arg, &removed_attributes);
   8452   if (removed_attributes
   8453       && (complain & tf_warning))
   8454     warning (OPT_Wignored_attributes,
   8455 	     "ignoring attributes on template argument %qT", arg);
   8456   return canon;
   8457 }
   8458 
   8459 /* And from inside dependent non-type arguments like sizeof(Type).  */
   8460 
   8461 static tree
   8462 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
   8463 {
   8464   if (!arg || arg == error_mark_node)
   8465     return arg;
   8466   bool removed_attributes = false;
   8467   tree canon = strip_typedefs_expr (arg, &removed_attributes);
   8468   if (removed_attributes
   8469       && (complain & tf_warning))
   8470     warning (OPT_Wignored_attributes,
   8471 	     "ignoring attributes in template argument %qE", arg);
   8472   return canon;
   8473 }
   8474 
   8475 /* A template declaration can be substituted for a constrained
   8476    template template parameter only when the argument is no more
   8477    constrained than the parameter.  */
   8478 
   8479 static bool
   8480 is_compatible_template_arg (tree parm, tree arg, tree args)
   8481 {
   8482   tree parm_cons = get_constraints (parm);
   8483 
   8484   /* For now, allow constrained template template arguments
   8485      and unconstrained template template parameters.  */
   8486   if (parm_cons == NULL_TREE)
   8487     return true;
   8488 
   8489   /* If the template parameter is constrained, we need to rewrite its
   8490      constraints in terms of the ARG's template parameters. This ensures
   8491      that all of the template parameter types will have the same depth.
   8492 
   8493      Note that this is only valid when coerce_template_template_parm is
   8494      true for the innermost template parameters of PARM and ARG. In other
   8495      words, because coercion is successful, this conversion will be valid.  */
   8496   tree new_args = NULL_TREE;
   8497   if (parm_cons)
   8498     {
   8499       tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
   8500       new_args = template_parms_level_to_args (aparms);
   8501       new_args = add_to_template_args (args, new_args);
   8502       ++processing_template_decl;
   8503       parm_cons = tsubst_constraint_info (parm_cons, new_args,
   8504 					  tf_none, NULL_TREE);
   8505       --processing_template_decl;
   8506       if (parm_cons == error_mark_node)
   8507         return false;
   8508     }
   8509 
   8510   return ttp_subsumes (parm_cons, arg);
   8511 }
   8512 
   8513 // Convert a placeholder argument into a binding to the original
   8514 // parameter. The original parameter is saved as the TREE_TYPE of
   8515 // ARG.
   8516 static inline tree
   8517 convert_wildcard_argument (tree parm, tree arg)
   8518 {
   8519   TREE_TYPE (arg) = parm;
   8520   return arg;
   8521 }
   8522 
   8523 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
   8524    because one of them is dependent.  But we need to represent the
   8525    conversion for the benefit of cp_tree_equal.  */
   8526 
   8527 static tree
   8528 maybe_convert_nontype_argument (tree type, tree arg, bool force)
   8529 {
   8530   /* Auto parms get no conversion.  */
   8531   if (type_uses_auto (type))
   8532     return arg;
   8533   /* ??? Do we need to push the IMPLICIT_CONV_EXPR into the pack expansion?
   8534      That would complicate other things, and it doesn't seem necessary.  */
   8535   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
   8536     return arg;
   8537   /* We don't need or want to add this conversion now if we're going to use the
   8538      argument for deduction.  */
   8539   if (!value_dependent_expression_p (arg))
   8540     force = false;
   8541   else if (!force)
   8542     return arg;
   8543 
   8544   type = cv_unqualified (type);
   8545   tree argtype = TREE_TYPE (arg);
   8546   if (argtype && same_type_p (type, argtype))
   8547     return arg;
   8548 
   8549   arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
   8550   IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
   8551   IMPLICIT_CONV_EXPR_FORCED (arg) = force;
   8552   return arg;
   8553 }
   8554 
   8555 /* Convert the indicated template ARG as necessary to match the
   8556    indicated template PARM.  Returns the converted ARG, or
   8557    error_mark_node if the conversion was unsuccessful.  Error and
   8558    warning messages are issued under control of COMPLAIN.  This
   8559    conversion is for the Ith parameter in the parameter list.  ARGS is
   8560    the full set of template arguments deduced so far.  */
   8561 
   8562 static tree
   8563 convert_template_argument (tree parm,
   8564 			   tree arg,
   8565 			   tree args,
   8566 			   tsubst_flags_t complain,
   8567 			   int i,
   8568 			   tree in_decl)
   8569 {
   8570   tree orig_arg;
   8571   tree val;
   8572   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
   8573 
   8574   if (parm == error_mark_node || error_operand_p (arg))
   8575     return error_mark_node;
   8576 
   8577   /* Trivially convert placeholders. */
   8578   if (TREE_CODE (arg) == WILDCARD_DECL)
   8579     return convert_wildcard_argument (parm, arg);
   8580 
   8581   if (arg == any_targ_node)
   8582     return arg;
   8583 
   8584   if (TREE_CODE (arg) == TREE_LIST
   8585       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
   8586     {
   8587       /* The template argument was the name of some
   8588 	 member function.  That's usually
   8589 	 invalid, but static members are OK.  In any
   8590 	 case, grab the underlying fields/functions
   8591 	 and issue an error later if required.  */
   8592       TREE_TYPE (arg) = unknown_type_node;
   8593     }
   8594 
   8595   orig_arg = arg;
   8596 
   8597   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
   8598   requires_type = (TREE_CODE (parm) == TYPE_DECL
   8599 		   || requires_tmpl_type);
   8600 
   8601   /* When determining whether an argument pack expansion is a template,
   8602      look at the pattern.  */
   8603   if (PACK_EXPANSION_P (arg))
   8604     arg = PACK_EXPANSION_PATTERN (arg);
   8605 
   8606   /* Deal with an injected-class-name used as a template template arg.  */
   8607   if (requires_tmpl_type && CLASS_TYPE_P (arg))
   8608     {
   8609       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
   8610       if (TREE_CODE (t) == TEMPLATE_DECL)
   8611 	{
   8612 	  if (cxx_dialect >= cxx11)
   8613 	    /* OK under DR 1004.  */;
   8614 	  else if (complain & tf_warning_or_error)
   8615 	    pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
   8616 		     " used as template template argument", TYPE_NAME (arg));
   8617 	  else if (flag_pedantic_errors)
   8618 	    t = arg;
   8619 
   8620 	  arg = t;
   8621 	}
   8622     }
   8623 
   8624   is_tmpl_type =
   8625     ((TREE_CODE (arg) == TEMPLATE_DECL
   8626       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
   8627      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
   8628      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
   8629      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
   8630 
   8631   if (is_tmpl_type
   8632       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
   8633 	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
   8634     arg = TYPE_STUB_DECL (arg);
   8635 
   8636   is_type = TYPE_P (arg) || is_tmpl_type;
   8637 
   8638   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
   8639       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
   8640     {
   8641       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
   8642 	{
   8643 	  if (complain & tf_error)
   8644 	    error ("invalid use of destructor %qE as a type", orig_arg);
   8645 	  return error_mark_node;
   8646 	}
   8647 
   8648       permerror (input_location,
   8649 		 "to refer to a type member of a template parameter, "
   8650 		 "use %<typename %E%>", orig_arg);
   8651 
   8652       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
   8653 				     TREE_OPERAND (arg, 1),
   8654 				     typename_type,
   8655 				     complain);
   8656       arg = orig_arg;
   8657       is_type = 1;
   8658     }
   8659   if (is_type != requires_type)
   8660     {
   8661       if (in_decl)
   8662 	{
   8663 	  if (complain & tf_error)
   8664 	    {
   8665 	      error ("type/value mismatch at argument %d in template "
   8666 		     "parameter list for %qD",
   8667 		     i + 1, in_decl);
   8668 	      if (is_type)
   8669 		{
   8670 		  /* The template argument is a type, but we're expecting
   8671 		     an expression.  */
   8672 		  inform (input_location,
   8673 			  "  expected a constant of type %qT, got %qT",
   8674 			  TREE_TYPE (parm),
   8675 			  (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
   8676 		  /* [temp.arg]/2: "In a template-argument, an ambiguity
   8677 		     between a type-id and an expression is resolved to a
   8678 		     type-id, regardless of the form of the corresponding
   8679 		     template-parameter."  So give the user a clue.  */
   8680 		  if (TREE_CODE (arg) == FUNCTION_TYPE)
   8681 		    inform (input_location, "  ambiguous template argument "
   8682 			    "for non-type template parameter is treated as "
   8683 			    "function type");
   8684 		}
   8685 	      else if (requires_tmpl_type)
   8686 		inform (input_location,
   8687 			"  expected a class template, got %qE", orig_arg);
   8688 	      else
   8689 		inform (input_location,
   8690 			"  expected a type, got %qE", orig_arg);
   8691 	    }
   8692 	}
   8693       return error_mark_node;
   8694     }
   8695   if (is_tmpl_type ^ requires_tmpl_type)
   8696     {
   8697       if (in_decl && (complain & tf_error))
   8698 	{
   8699 	  error ("type/value mismatch at argument %d in template "
   8700 		 "parameter list for %qD",
   8701 		 i + 1, in_decl);
   8702 	  if (is_tmpl_type)
   8703 	    inform (input_location,
   8704 		    "  expected a type, got %qT", DECL_NAME (arg));
   8705 	  else
   8706 	    inform (input_location,
   8707 		    "  expected a class template, got %qT", orig_arg);
   8708 	}
   8709       return error_mark_node;
   8710     }
   8711 
   8712   if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
   8713     /* We already did the appropriate conversion when packing args.  */
   8714     val = orig_arg;
   8715   else if (is_type)
   8716     {
   8717       if (requires_tmpl_type)
   8718 	{
   8719 	  if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
   8720 	    /* The number of argument required is not known yet.
   8721 	       Just accept it for now.  */
   8722 	    val = orig_arg;
   8723 	  else
   8724 	    {
   8725 	      /* Strip alias templates that are equivalent to another
   8726 		 template.  */
   8727 	      arg = get_underlying_template (arg);
   8728 
   8729 	      if (coerce_template_template_parms (parm, arg,
   8730 						  complain, in_decl,
   8731 						  args))
   8732 		{
   8733 		  val = arg;
   8734 
   8735 		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
   8736 		     TEMPLATE_DECL.  */
   8737 		  if (val != error_mark_node)
   8738                     {
   8739                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
   8740                         val = TREE_TYPE (val);
   8741 		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
   8742 			val = make_pack_expansion (val, complain);
   8743                     }
   8744 		}
   8745 	      else
   8746 		{
   8747 		  if (in_decl && (complain & tf_error))
   8748 		    {
   8749 		      error ("type/value mismatch at argument %d in "
   8750 			     "template parameter list for %qD",
   8751 			     i + 1, in_decl);
   8752 		      inform (input_location,
   8753 			      "  expected a template of type %qD, got %qT",
   8754 			      parm, orig_arg);
   8755 		    }
   8756 
   8757 		  val = error_mark_node;
   8758 		}
   8759 
   8760               // Check that the constraints are compatible before allowing the
   8761               // substitution.
   8762               if (val != error_mark_node)
   8763 		if (!is_compatible_template_arg (parm, arg, args))
   8764                   {
   8765 		    if (in_decl && (complain & tf_error))
   8766                       {
   8767                         error ("constraint mismatch at argument %d in "
   8768                                "template parameter list for %qD",
   8769                                i + 1, in_decl);
   8770                         inform (input_location, "  expected %qD but got %qD",
   8771                                 parm, arg);
   8772                       }
   8773 		    val = error_mark_node;
   8774                   }
   8775 	    }
   8776 	}
   8777       else
   8778 	val = orig_arg;
   8779       /* We only form one instance of each template specialization.
   8780 	 Therefore, if we use a non-canonical variant (i.e., a
   8781 	 typedef), any future messages referring to the type will use
   8782 	 the typedef, which is confusing if those future uses do not
   8783 	 themselves also use the typedef.  */
   8784       if (TYPE_P (val))
   8785 	val = canonicalize_type_argument (val, complain);
   8786     }
   8787   else
   8788     {
   8789       tree t = TREE_TYPE (parm);
   8790 
   8791       if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
   8792 	  > TMPL_ARGS_DEPTH (args))
   8793 	/* We don't have enough levels of args to do any substitution.  This
   8794 	   can happen in the context of -fnew-ttp-matching.  */;
   8795       else if (tree a = type_uses_auto (t))
   8796 	{
   8797 	  t = do_auto_deduction (t, arg, a, complain, adc_unify, args,
   8798 				 LOOKUP_IMPLICIT, /*tmpl=*/in_decl);
   8799 	  if (t == error_mark_node)
   8800 	    return error_mark_node;
   8801 	}
   8802       else
   8803 	t = tsubst (t, args, complain, in_decl);
   8804 
   8805       /* Perform array-to-pointer and function-to-pointer conversion
   8806 	 as per [temp.param]/10.  */
   8807       t = type_decays_to (t);
   8808 
   8809       if (invalid_nontype_parm_type_p (t, complain))
   8810 	return error_mark_node;
   8811 
   8812       /* Drop top-level cv-qualifiers on the substituted/deduced type of
   8813 	 this non-type template parameter, as per [temp.param]/6.  */
   8814       t = cv_unqualified (t);
   8815 
   8816       if (t != TREE_TYPE (parm))
   8817 	t = canonicalize_type_argument (t, complain);
   8818 
   8819       /* We need to handle arguments for alias or concept templates
   8820 	 differently: we need to force building an IMPLICIT_CONV_EXPR, because
   8821 	 these arguments are going to be substituted directly into the
   8822 	 dependent type; they might not get another chance at
   8823 	 convert_nontype_argument.  But if the argument ends up here again for
   8824 	 a template that isn't one of those, remove the conversion for
   8825 	 consistency between naming the same dependent type directly or through
   8826 	 an alias.  */
   8827       bool force_conv = in_decl && (DECL_ALIAS_TEMPLATE_P (in_decl)
   8828 				    || concept_definition_p (in_decl));
   8829       if (!force_conv
   8830 	  && TREE_CODE (orig_arg) == IMPLICIT_CONV_EXPR
   8831 	  && IMPLICIT_CONV_EXPR_FORCED (orig_arg)
   8832 	  && same_type_p (TREE_TYPE (orig_arg), t))
   8833 	orig_arg = TREE_OPERAND (orig_arg, 0);
   8834 
   8835       if (!type_dependent_expression_p (orig_arg)
   8836 	  && !uses_template_parms (t))
   8837 	/* We used to call digest_init here.  However, digest_init
   8838 	   will report errors, which we don't want when complain
   8839 	   is zero.  More importantly, digest_init will try too
   8840 	   hard to convert things: for example, `0' should not be
   8841 	   converted to pointer type at this point according to
   8842 	   the standard.  Accepting this is not merely an
   8843 	   extension, since deciding whether or not these
   8844 	   conversions can occur is part of determining which
   8845 	   function template to call, or whether a given explicit
   8846 	   argument specification is valid.  */
   8847 	val = convert_nontype_argument (t, orig_arg, complain);
   8848       else
   8849 	{
   8850 	  val = canonicalize_expr_argument (orig_arg, complain);
   8851 	  val = maybe_convert_nontype_argument (t, val, force_conv);
   8852 	}
   8853 
   8854       if (val == NULL_TREE)
   8855 	val = error_mark_node;
   8856       else if (val == error_mark_node && (complain & tf_error))
   8857 	error_at (cp_expr_loc_or_input_loc (orig_arg),
   8858 		  "could not convert template argument %qE from %qT to %qT",
   8859 		  orig_arg, TREE_TYPE (orig_arg), t);
   8860 
   8861       if (INDIRECT_REF_P (val))
   8862         {
   8863           /* Reject template arguments that are references to built-in
   8864              functions with no library fallbacks.  */
   8865           const_tree inner = TREE_OPERAND (val, 0);
   8866 	  const_tree innertype = TREE_TYPE (inner);
   8867 	  if (innertype
   8868 	      && TYPE_REF_P (innertype)
   8869 	      && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
   8870 	      && TREE_OPERAND_LENGTH (inner) > 0
   8871               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
   8872               return error_mark_node;
   8873         }
   8874 
   8875       if (TREE_CODE (val) == SCOPE_REF)
   8876 	{
   8877 	  /* Strip typedefs from the SCOPE_REF.  */
   8878 	  tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
   8879 	  tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
   8880 						   complain);
   8881 	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
   8882 				      QUALIFIED_NAME_IS_TEMPLATE (val));
   8883 	}
   8884     }
   8885 
   8886   return val;
   8887 }
   8888 
   8889 /* Coerces the remaining template arguments in INNER_ARGS (from
   8890    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
   8891    Returns the coerced argument pack. PARM_IDX is the position of this
   8892    parameter in the template parameter list. ARGS is the original
   8893    template argument list.  */
   8894 static tree
   8895 coerce_template_parameter_pack (tree parms,
   8896                                 int parm_idx,
   8897                                 tree args,
   8898                                 tree inner_args,
   8899                                 int arg_idx,
   8900                                 tree new_args,
   8901                                 int* lost,
   8902                                 tree in_decl,
   8903                                 tsubst_flags_t complain)
   8904 {
   8905   tree parm = TREE_VEC_ELT (parms, parm_idx);
   8906   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
   8907   tree packed_args;
   8908   tree argument_pack;
   8909   tree packed_parms = NULL_TREE;
   8910 
   8911   if (arg_idx > nargs)
   8912     arg_idx = nargs;
   8913 
   8914   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
   8915     {
   8916       /* When the template parameter is a non-type template parameter pack
   8917          or template template parameter pack whose type or template
   8918          parameters use parameter packs, we know exactly how many arguments
   8919          we are looking for.  Build a vector of the instantiated decls for
   8920          these template parameters in PACKED_PARMS.  */
   8921       /* We can't use make_pack_expansion here because it would interpret a
   8922 	 _DECL as a use rather than a declaration.  */
   8923       tree decl = TREE_VALUE (parm);
   8924       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
   8925       PACK_EXPANSION_PATTERN (exp) = decl;
   8926       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
   8927       SET_TYPE_STRUCTURAL_EQUALITY (exp);
   8928 
   8929       TREE_VEC_LENGTH (args)--;
   8930       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
   8931       TREE_VEC_LENGTH (args)++;
   8932 
   8933       if (packed_parms == error_mark_node)
   8934         return error_mark_node;
   8935 
   8936       /* If we're doing a partial instantiation of a member template,
   8937          verify that all of the types used for the non-type
   8938          template parameter pack are, in fact, valid for non-type
   8939          template parameters.  */
   8940       if (arg_idx < nargs
   8941           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
   8942         {
   8943           int j, len = TREE_VEC_LENGTH (packed_parms);
   8944           for (j = 0; j < len; ++j)
   8945             {
   8946               tree t = TREE_VEC_ELT (packed_parms, j);
   8947               if (TREE_CODE (t) == PARM_DECL
   8948 		  && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
   8949                 return error_mark_node;
   8950             }
   8951 	  /* We don't know how many args we have yet, just
   8952 	     use the unconverted ones for now.  */
   8953 	  return NULL_TREE;
   8954         }
   8955 
   8956       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
   8957     }
   8958   /* Check if we have a placeholder pack, which indicates we're
   8959      in the context of a introduction list.  In that case we want
   8960      to match this pack to the single placeholder.  */
   8961   else if (arg_idx < nargs
   8962            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
   8963            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
   8964     {
   8965       nargs = arg_idx + 1;
   8966       packed_args = make_tree_vec (1);
   8967     }
   8968   else
   8969     packed_args = make_tree_vec (nargs - arg_idx);
   8970 
   8971   /* Convert the remaining arguments, which will be a part of the
   8972      parameter pack "parm".  */
   8973   int first_pack_arg = arg_idx;
   8974   for (; arg_idx < nargs; ++arg_idx)
   8975     {
   8976       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
   8977       tree actual_parm = TREE_VALUE (parm);
   8978       int pack_idx = arg_idx - first_pack_arg;
   8979 
   8980       if (packed_parms)
   8981         {
   8982 	  /* Once we've packed as many args as we have types, stop.  */
   8983 	  if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
   8984 	    break;
   8985 	  else if (PACK_EXPANSION_P (arg))
   8986 	    /* We don't know how many args we have yet, just
   8987 	       use the unconverted ones for now.  */
   8988 	    return NULL_TREE;
   8989 	  else
   8990 	    actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
   8991         }
   8992 
   8993       if (arg == error_mark_node)
   8994 	{
   8995 	  if (complain & tf_error)
   8996 	    error ("template argument %d is invalid", arg_idx + 1);
   8997 	}
   8998       else
   8999 	arg = convert_template_argument (actual_parm,
   9000 					 arg, new_args, complain, parm_idx,
   9001 					 in_decl);
   9002       if (arg == error_mark_node)
   9003         (*lost)++;
   9004       TREE_VEC_ELT (packed_args, pack_idx) = arg;
   9005     }
   9006 
   9007   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
   9008       && TREE_VEC_LENGTH (packed_args) > 0)
   9009     {
   9010       if (complain & tf_error)
   9011 	error ("wrong number of template arguments (%d, should be %d)",
   9012 	       arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
   9013       return error_mark_node;
   9014     }
   9015 
   9016   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
   9017       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
   9018     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
   9019   else
   9020     {
   9021       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
   9022       TREE_CONSTANT (argument_pack) = 1;
   9023     }
   9024 
   9025   ARGUMENT_PACK_ARGS (argument_pack) = packed_args;
   9026   if (CHECKING_P)
   9027     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
   9028 					 TREE_VEC_LENGTH (packed_args));
   9029   return argument_pack;
   9030 }
   9031 
   9032 /* Returns the number of pack expansions in the template argument vector
   9033    ARGS.  */
   9034 
   9035 static int
   9036 pack_expansion_args_count (tree args)
   9037 {
   9038   int i;
   9039   int count = 0;
   9040   if (args)
   9041     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
   9042       {
   9043 	tree elt = TREE_VEC_ELT (args, i);
   9044 	if (elt && PACK_EXPANSION_P (elt))
   9045 	  ++count;
   9046       }
   9047   return count;
   9048 }
   9049 
   9050 /* Convert all template arguments to their appropriate types, and
   9051    return a vector containing the innermost resulting template
   9052    arguments.  If any error occurs, return error_mark_node. Error and
   9053    warning messages are issued under control of COMPLAIN.
   9054 
   9055    If PARMS represents all template parameters levels, this function
   9056    returns a vector of vectors representing all the resulting argument
   9057    levels.  Note that in this case, only the innermost arguments are
   9058    coerced because the outermost ones are supposed to have been coerced
   9059    already.  Otherwise, if PARMS represents only (the innermost) vector
   9060    of parameters, this function returns a vector containing just the
   9061    innermost resulting arguments.
   9062 
   9063    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
   9064    for arguments not specified in ARGS.  If REQUIRE_ALL_ARGS is true,
   9065    arguments not specified in ARGS must have default arguments which
   9066    we'll use to fill in ARGS.  */
   9067 
   9068 tree
   9069 coerce_template_parms (tree parms,
   9070 		       tree args,
   9071 		       tree in_decl,
   9072 		       tsubst_flags_t complain,
   9073 		       bool require_all_args /* = true */)
   9074 {
   9075   int nparms, nargs, parm_idx, arg_idx, lost = 0;
   9076   tree orig_inner_args;
   9077   tree inner_args;
   9078 
   9079   /* When used as a boolean value, indicates whether this is a
   9080      variadic template parameter list. Since it's an int, we can also
   9081      subtract it from nparms to get the number of non-variadic
   9082      parameters.  */
   9083   int variadic_p = 0;
   9084   int variadic_args_p = 0;
   9085   int post_variadic_parms = 0;
   9086 
   9087   /* Adjustment to nparms for fixed parameter packs.  */
   9088   int fixed_pack_adjust = 0;
   9089   int fixed_packs = 0;
   9090   int missing = 0;
   9091 
   9092   /* Likewise for parameters with default arguments.  */
   9093   int default_p = 0;
   9094 
   9095   if (args == error_mark_node)
   9096     return error_mark_node;
   9097 
   9098   bool return_full_args = false;
   9099   if (TREE_CODE (parms) == TREE_LIST)
   9100     {
   9101       if (TMPL_PARMS_DEPTH (parms) > 1)
   9102 	{
   9103 	  gcc_assert (TMPL_PARMS_DEPTH (parms) == TMPL_ARGS_DEPTH (args));
   9104 	  return_full_args = true;
   9105 	}
   9106       parms = INNERMOST_TEMPLATE_PARMS (parms);
   9107     }
   9108 
   9109   nparms = TREE_VEC_LENGTH (parms);
   9110 
   9111   /* Determine if there are any parameter packs or default arguments.  */
   9112   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
   9113     {
   9114       tree parm = TREE_VEC_ELT (parms, parm_idx);
   9115       if (variadic_p)
   9116 	++post_variadic_parms;
   9117       if (template_parameter_pack_p (TREE_VALUE (parm)))
   9118 	++variadic_p;
   9119       if (TREE_PURPOSE (parm))
   9120 	++default_p;
   9121     }
   9122 
   9123   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
   9124   /* If there are no parameters that follow a parameter pack, we need to
   9125      expand any argument packs so that we can deduce a parameter pack from
   9126      some non-packed args followed by an argument pack, as in variadic85.C.
   9127      If there are such parameters, we need to leave argument packs intact
   9128      so the arguments are assigned properly.  This can happen when dealing
   9129      with a nested class inside a partial specialization of a class
   9130      template, as in variadic92.C, or when deducing a template parameter pack
   9131      from a sub-declarator, as in variadic114.C.  */
   9132   if (!post_variadic_parms)
   9133     inner_args = expand_template_argument_pack (inner_args);
   9134 
   9135   /* Count any pack expansion args.  */
   9136   variadic_args_p = pack_expansion_args_count (inner_args);
   9137 
   9138   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
   9139   if ((nargs - variadic_args_p > nparms && !variadic_p)
   9140       || (nargs < nparms - variadic_p
   9141 	  && require_all_args
   9142 	  && !variadic_args_p
   9143 	  && (TREE_VEC_ELT (parms, nargs) != error_mark_node
   9144 	      && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)))))
   9145     {
   9146     bad_nargs:
   9147       if (complain & tf_error)
   9148 	{
   9149           if (variadic_p || default_p)
   9150             {
   9151               nparms -= variadic_p + default_p;
   9152 	      error ("wrong number of template arguments "
   9153 		     "(%d, should be at least %d)", nargs, nparms);
   9154             }
   9155 	  else
   9156 	     error ("wrong number of template arguments "
   9157 		    "(%d, should be %d)", nargs, nparms);
   9158 
   9159 	  if (in_decl)
   9160 	    inform (DECL_SOURCE_LOCATION (in_decl),
   9161 		    "provided for %qD", in_decl);
   9162 	}
   9163 
   9164       return error_mark_node;
   9165     }
   9166   /* We can't pass a pack expansion to a non-pack parameter of an alias
   9167      template (DR 1430).  */
   9168   else if (in_decl
   9169 	   && (DECL_ALIAS_TEMPLATE_P (in_decl)
   9170 	       || concept_definition_p (in_decl))
   9171 	   && variadic_args_p
   9172 	   && nargs - variadic_args_p < nparms - variadic_p)
   9173     {
   9174       if (complain & tf_error)
   9175 	{
   9176 	  for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
   9177 	    {
   9178 	      tree arg = TREE_VEC_ELT (inner_args, i);
   9179 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
   9180 
   9181 	      if (PACK_EXPANSION_P (arg)
   9182 		  && !template_parameter_pack_p (parm))
   9183 		{
   9184 		  if (DECL_ALIAS_TEMPLATE_P (in_decl))
   9185 		    error_at (location_of (arg),
   9186 			      "pack expansion argument for non-pack parameter "
   9187 			      "%qD of alias template %qD", parm, in_decl);
   9188 		  else
   9189 		    error_at (location_of (arg),
   9190 			      "pack expansion argument for non-pack parameter "
   9191 			      "%qD of concept %qD", parm, in_decl);
   9192 		  inform (DECL_SOURCE_LOCATION (parm), "declared here");
   9193 		  goto found;
   9194 		}
   9195 	    }
   9196 	  gcc_unreachable ();
   9197 	found:;
   9198 	}
   9199       return error_mark_node;
   9200     }
   9201 
   9202   /* We need to evaluate the template arguments, even though this
   9203      template-id may be nested within a "sizeof".  */
   9204   cp_evaluated ev;
   9205 
   9206   tree new_args = add_outermost_template_args (args, make_tree_vec (nparms));
   9207   tree& new_inner_args = TMPL_ARGS_LEVEL (new_args, TMPL_ARGS_DEPTH (new_args));
   9208   int pack_adjust = 0;
   9209   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
   9210     {
   9211       tree arg;
   9212       tree parm;
   9213 
   9214       /* Get the Ith template parameter.  */
   9215       parm = TREE_VEC_ELT (parms, parm_idx);
   9216 
   9217       if (parm == error_mark_node)
   9218 	{
   9219 	  TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
   9220 	  continue;
   9221 	}
   9222 
   9223       /* Calculate the next argument.  */
   9224       if (arg_idx < nargs)
   9225 	arg = TREE_VEC_ELT (inner_args, arg_idx);
   9226       else
   9227 	arg = NULL_TREE;
   9228 
   9229       if (template_parameter_pack_p (TREE_VALUE (parm))
   9230 	  && (arg || require_all_args || !(complain & tf_partial))
   9231 	  && !(arg && ARGUMENT_PACK_P (arg)))
   9232         {
   9233 	  /* Some arguments will be placed in the
   9234 	     template parameter pack PARM.  */
   9235 	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
   9236 						inner_args, arg_idx,
   9237 						new_args, &lost,
   9238 						in_decl, complain);
   9239 
   9240 	  if (arg == NULL_TREE)
   9241 	    {
   9242 	      /* We don't know how many args we have yet, just use the
   9243 		 unconverted (and still packed) ones for now.  */
   9244 	      new_inner_args = orig_inner_args;
   9245 	      arg_idx = nargs;
   9246 	      break;
   9247 	    }
   9248 
   9249           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
   9250 
   9251           /* Store this argument.  */
   9252           if (arg == error_mark_node)
   9253 	    {
   9254 	      lost++;
   9255 	      /* We are done with all of the arguments.  */
   9256 	      arg_idx = nargs;
   9257 	      break;
   9258 	    }
   9259 	  else
   9260 	    {
   9261 	      pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
   9262 	      arg_idx += pack_adjust;
   9263 	      if (fixed_parameter_pack_p (TREE_VALUE (parm)))
   9264 		{
   9265 		  ++fixed_packs;
   9266 		  fixed_pack_adjust += pack_adjust;
   9267 		}
   9268 	    }
   9269 
   9270           continue;
   9271         }
   9272       else if (arg)
   9273 	{
   9274           if (PACK_EXPANSION_P (arg))
   9275             {
   9276 	      /* "If every valid specialization of a variadic template
   9277 		 requires an empty template parameter pack, the template is
   9278 		 ill-formed, no diagnostic required."  So check that the
   9279 		 pattern works with this parameter.  */
   9280 	      tree pattern = PACK_EXPANSION_PATTERN (arg);
   9281 	      tree conv = convert_template_argument (TREE_VALUE (parm),
   9282 						     pattern, new_args,
   9283 						     complain, parm_idx,
   9284 						     in_decl);
   9285 	      if (conv == error_mark_node)
   9286 		{
   9287 		  if (complain & tf_error)
   9288 		    inform (input_location, "so any instantiation with a "
   9289 			    "non-empty parameter pack would be ill-formed");
   9290 		  ++lost;
   9291 		}
   9292 	      else if (TYPE_P (conv) && !TYPE_P (pattern))
   9293 		/* Recover from missing typename.  */
   9294 		TREE_VEC_ELT (inner_args, arg_idx)
   9295 		  = make_pack_expansion (conv, complain);
   9296 
   9297               /* We don't know how many args we have yet, just
   9298                  use the unconverted ones for now.  */
   9299               new_inner_args = inner_args;
   9300 	      arg_idx = nargs;
   9301               break;
   9302             }
   9303         }
   9304       else if (require_all_args)
   9305 	{
   9306 	  /* There must be a default arg in this case.  */
   9307 	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
   9308 				     complain, in_decl);
   9309 	  /* The position of the first default template argument,
   9310 	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
   9311 	     Record that.  */
   9312 	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
   9313 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
   9314 						 arg_idx - pack_adjust);
   9315 	}
   9316       else
   9317 	break;
   9318 
   9319       if (arg == error_mark_node)
   9320 	{
   9321 	  if (complain & tf_error)
   9322 	    error ("template argument %d is invalid", arg_idx + 1);
   9323 	}
   9324       else if (!arg)
   9325 	{
   9326 	  /* This can occur if there was an error in the template
   9327 	     parameter list itself (which we would already have
   9328 	     reported) that we are trying to recover from, e.g., a class
   9329 	     template with a parameter list such as
   9330 	     template<typename..., typename> (cpp0x/variadic150.C).  */
   9331 	  ++lost;
   9332 
   9333 	  /* This can also happen with a fixed parameter pack (71834).  */
   9334 	  if (arg_idx >= nargs)
   9335 	    ++missing;
   9336 	}
   9337       else
   9338 	arg = convert_template_argument (TREE_VALUE (parm),
   9339 					 arg, new_args, complain,
   9340                                          parm_idx, in_decl);
   9341 
   9342       if (arg == error_mark_node)
   9343 	lost++;
   9344 
   9345       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
   9346     }
   9347 
   9348   if (missing || arg_idx < nargs - variadic_args_p)
   9349     {
   9350       /* If we had fixed parameter packs, we didn't know how many arguments we
   9351 	 actually needed earlier; now we do.  */
   9352       nparms += fixed_pack_adjust;
   9353       variadic_p -= fixed_packs;
   9354       goto bad_nargs;
   9355     }
   9356 
   9357   if (arg_idx < nargs)
   9358     {
   9359       /* We had some pack expansion arguments that will only work if the packs
   9360 	 are empty, but wait until instantiation time to complain.
   9361 	 See variadic-ttp3.C.  */
   9362 
   9363       /* Except that we can't provide empty packs to alias templates or
   9364          concepts when there are no corresponding parameters. Basically,
   9365          we can get here with this:
   9366 
   9367              template<typename T> concept C = true;
   9368 
   9369              template<typename... Args>
   9370 	       requires C<Args...>
   9371              void f();
   9372 
   9373          When parsing C<Args...>, we try to form a concept check of
   9374          C<?, Args...>. Without the extra check for substituting an empty
   9375          pack past the last parameter, we can accept the check as valid.
   9376 
   9377          FIXME: This may be valid for alias templates (but I doubt it).
   9378 
   9379          FIXME: The error could be better also.   */
   9380       if (in_decl && concept_definition_p (in_decl))
   9381 	{
   9382 	  if (complain & tf_error)
   9383 	    error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
   9384 		      "too many arguments");
   9385 	  return error_mark_node;
   9386 	}
   9387 
   9388       int len = nparms + (nargs - arg_idx);
   9389       tree args = make_tree_vec (len);
   9390       int i = 0;
   9391       for (; i < nparms; ++i)
   9392 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
   9393       for (; i < len; ++i, ++arg_idx)
   9394 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
   9395 					       arg_idx - pack_adjust);
   9396       new_inner_args = args;
   9397     }
   9398 
   9399   if (lost)
   9400     {
   9401       gcc_assert (!(complain & tf_error) || seen_error ());
   9402       return error_mark_node;
   9403     }
   9404 
   9405   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
   9406     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
   9407 					 TREE_VEC_LENGTH (new_inner_args));
   9408 
   9409   return return_full_args ? new_args : new_inner_args;
   9410 }
   9411 
   9412 /* Returns true if T is a wrapper to make a C++20 template parameter
   9413    object const.  */
   9414 
   9415 static bool
   9416 class_nttp_const_wrapper_p (tree t)
   9417 {
   9418   if (cxx_dialect < cxx20)
   9419     return false;
   9420   return (TREE_CODE (t) == VIEW_CONVERT_EXPR
   9421 	  && CP_TYPE_CONST_P (TREE_TYPE (t))
   9422 	  && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
   9423 }
   9424 
   9425 /* Returns 1 if template args OT and NT are equivalent.  */
   9426 
   9427 int
   9428 template_args_equal (tree ot, tree nt)
   9429 {
   9430   if (nt == ot)
   9431     return 1;
   9432   if (nt == NULL_TREE || ot == NULL_TREE)
   9433     return false;
   9434   if (nt == any_targ_node || ot == any_targ_node)
   9435     return true;
   9436 
   9437   if (class_nttp_const_wrapper_p (nt))
   9438     nt = TREE_OPERAND (nt, 0);
   9439   if (class_nttp_const_wrapper_p (ot))
   9440     ot = TREE_OPERAND (ot, 0);
   9441 
   9442   /* DR 1558: Don't treat an alias template specialization with dependent
   9443      arguments as equivalent to its underlying type when used as a template
   9444      argument; we need them to be distinct so that we substitute into the
   9445      specialization arguments at instantiation time.  And aliases can't be
   9446      equivalent without being ==, so we don't need to look any deeper.
   9447 
   9448      During partial ordering, however, we need to treat them normally so we can
   9449      order uses of the same alias with different cv-qualification (79960).  */
   9450   auto cso = make_temp_override (comparing_dependent_aliases);
   9451   if (!comparing_for_partial_ordering)
   9452     ++comparing_dependent_aliases;
   9453 
   9454   if (TREE_CODE (nt) == TREE_VEC || TREE_CODE (ot) == TREE_VEC)
   9455     /* For member templates */
   9456     return TREE_CODE (ot) == TREE_CODE (nt) && comp_template_args (ot, nt);
   9457   else if (PACK_EXPANSION_P (ot) || PACK_EXPANSION_P (nt))
   9458     return (PACK_EXPANSION_P (ot) && PACK_EXPANSION_P (nt)
   9459 	    && template_args_equal (PACK_EXPANSION_PATTERN (ot),
   9460 				    PACK_EXPANSION_PATTERN (nt))
   9461 	    && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
   9462 				    PACK_EXPANSION_EXTRA_ARGS (nt)));
   9463   else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
   9464     return cp_tree_equal (ot, nt);
   9465   else if (TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
   9466     gcc_unreachable ();
   9467   else if (TYPE_P (nt) || TYPE_P (ot))
   9468     {
   9469       if (!(TYPE_P (nt) && TYPE_P (ot)))
   9470 	return false;
   9471       return same_type_p (ot, nt);
   9472     }
   9473   else
   9474     {
   9475       /* Try to treat a template non-type argument that has been converted
   9476 	 to the parameter type as equivalent to one that hasn't yet.  */
   9477       for (enum tree_code code1 = TREE_CODE (ot);
   9478 	   CONVERT_EXPR_CODE_P (code1)
   9479 	     || code1 == NON_LVALUE_EXPR;
   9480 	   code1 = TREE_CODE (ot))
   9481 	ot = TREE_OPERAND (ot, 0);
   9482 
   9483       for (enum tree_code code2 = TREE_CODE (nt);
   9484 	   CONVERT_EXPR_CODE_P (code2)
   9485 	     || code2 == NON_LVALUE_EXPR;
   9486 	   code2 = TREE_CODE (nt))
   9487 	nt = TREE_OPERAND (nt, 0);
   9488 
   9489       return cp_tree_equal (ot, nt);
   9490     }
   9491 }
   9492 
   9493 /* Returns true iff the OLDARGS and NEWARGS are in fact identical sets of
   9494    template arguments.  Returns false otherwise, and updates OLDARG_PTR and
   9495    NEWARG_PTR with the offending arguments if they are non-NULL.  */
   9496 
   9497 bool
   9498 comp_template_args (tree oldargs, tree newargs,
   9499 		    tree *oldarg_ptr /* = NULL */, tree *newarg_ptr /* = NULL */)
   9500 {
   9501   if (oldargs == newargs)
   9502     return true;
   9503 
   9504   if (!oldargs || !newargs)
   9505     return false;
   9506 
   9507   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
   9508     return false;
   9509 
   9510   for (int i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
   9511     {
   9512       tree nt = TREE_VEC_ELT (newargs, i);
   9513       tree ot = TREE_VEC_ELT (oldargs, i);
   9514 
   9515       if (! template_args_equal (ot, nt))
   9516 	{
   9517 	  if (oldarg_ptr != NULL)
   9518 	    *oldarg_ptr = ot;
   9519 	  if (newarg_ptr != NULL)
   9520 	    *newarg_ptr = nt;
   9521 	  return false;
   9522 	}
   9523     }
   9524   return true;
   9525 }
   9526 
   9527 static bool
   9528 comp_template_args_porder (tree oargs, tree nargs)
   9529 {
   9530   ++comparing_for_partial_ordering;
   9531   bool equal = comp_template_args (oargs, nargs);
   9532   --comparing_for_partial_ordering;
   9533   return equal;
   9534 }
   9535 
   9536 /* Implement a freelist interface for objects of type T.
   9537 
   9538    Head is a separate object, rather than a regular member, so that we
   9539    can define it as a GTY deletable pointer, which is highly
   9540    desirable.  A data member could be declared that way, but then the
   9541    containing object would implicitly get GTY((user)), which would
   9542    prevent us from instantiating freelists as global objects.
   9543    Although this way we can create freelist global objects, they're
   9544    such thin wrappers that instantiating temporaries at every use
   9545    loses nothing and saves permanent storage for the freelist object.
   9546 
   9547    Member functions next, anew, poison and reinit have default
   9548    implementations that work for most of the types we're interested
   9549    in, but if they don't work for some type, they should be explicitly
   9550    specialized.  See the comments before them for requirements, and
   9551    the example specializations for the tree_list_freelist.  */
   9552 template <typename T>
   9553 class freelist
   9554 {
   9555   /* Return the next object in a chain.  We could just do type
   9556      punning, but if we access the object with its underlying type, we
   9557      avoid strict-aliasing trouble.  This needs only work between
   9558      poison and reinit.  */
   9559   static T *&next (T *obj) { return obj->next; }
   9560 
   9561   /* Return a newly allocated, uninitialized or minimally-initialized
   9562      object of type T.  Any initialization performed by anew should
   9563      either remain across the life of the object and the execution of
   9564      poison, or be redone by reinit.  */
   9565   static T *anew () { return ggc_alloc<T> (); }
   9566 
   9567   /* Optionally scribble all over the bits holding the object, so that
   9568      they become (mostly?) uninitialized memory.  This is called while
   9569      preparing to make the object part of the free list.  */
   9570   static void poison (T *obj) {
   9571     T *p ATTRIBUTE_UNUSED = obj;
   9572     T **q ATTRIBUTE_UNUSED = &next (obj);
   9573 
   9574 #ifdef ENABLE_GC_CHECKING
   9575     /* Poison the data, to indicate the data is garbage.  */
   9576     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
   9577     memset (p, 0xa5, sizeof (*p));
   9578 #endif
   9579     /* Let valgrind know the object is free.  */
   9580     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
   9581 
   9582     /* Let valgrind know the next portion of the object is available,
   9583        but uninitialized.  */
   9584     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
   9585   }
   9586 
   9587   /* Bring an object that underwent at least one lifecycle after anew
   9588      and before the most recent free and poison, back to a usable
   9589      state, reinitializing whatever is needed for it to be
   9590      functionally equivalent to an object just allocated and returned
   9591      by anew.  This may poison or clear the next field, used by
   9592      freelist housekeeping after poison was called.  */
   9593   static void reinit (T *obj) {
   9594     T **q ATTRIBUTE_UNUSED = &next (obj);
   9595 
   9596 #ifdef ENABLE_GC_CHECKING
   9597     memset (q, 0xa5, sizeof (*q));
   9598 #endif
   9599     /* Let valgrind know the entire object is available, but
   9600        uninitialized.  */
   9601     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
   9602   }
   9603 
   9604   /* Reference a GTY-deletable pointer that points to the first object
   9605      in the free list proper.  */
   9606   T *&head;
   9607 public:
   9608   /* Construct a freelist object chaining objects off of HEAD.  */
   9609   freelist (T *&head) : head(head) {}
   9610 
   9611   /* Add OBJ to the free object list.  The former head becomes OBJ's
   9612      successor.  */
   9613   void free (T *obj)
   9614   {
   9615     poison (obj);
   9616     next (obj) = head;
   9617     head = obj;
   9618   }
   9619 
   9620   /* Take an object from the free list, if one is available, or
   9621      allocate a new one.  Objects taken from the free list should be
   9622      regarded as filled with garbage, except for bits that are
   9623      configured to be preserved across free and alloc.  */
   9624   T *alloc ()
   9625   {
   9626     if (head)
   9627       {
   9628 	T *obj = head;
   9629 	head = next (head);
   9630 	reinit (obj);
   9631 	return obj;
   9632       }
   9633     else
   9634       return anew ();
   9635   }
   9636 };
   9637 
   9638 /* Explicitly specialize the interfaces for freelist<tree_node>: we
   9639    want to allocate a TREE_LIST using the usual interface, and ensure
   9640    TREE_CHAIN remains functional.  Alas, we have to duplicate a bit of
   9641    build_tree_list logic in reinit, so this could go out of sync.  */
   9642 template <>
   9643 inline tree &
   9644 freelist<tree_node>::next (tree obj)
   9645 {
   9646   return TREE_CHAIN (obj);
   9647 }
   9648 template <>
   9649 inline tree
   9650 freelist<tree_node>::anew ()
   9651 {
   9652   return build_tree_list (NULL, NULL);
   9653 }
   9654 template <>
   9655 inline void
   9656 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
   9657 {
   9658   int size ATTRIBUTE_UNUSED = sizeof (tree_list);
   9659   tree p ATTRIBUTE_UNUSED = obj;
   9660   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
   9661   tree *q ATTRIBUTE_UNUSED = &next (obj);
   9662 
   9663 #ifdef ENABLE_GC_CHECKING
   9664   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
   9665 
   9666   /* Poison the data, to indicate the data is garbage.  */
   9667   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
   9668   memset (p, 0xa5, size);
   9669 #endif
   9670   /* Let valgrind know the object is free.  */
   9671   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
   9672   /* But we still want to use the TREE_CODE and TREE_CHAIN parts.  */
   9673   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
   9674   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
   9675 
   9676 #ifdef ENABLE_GC_CHECKING
   9677   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
   9678   /* Keep TREE_CHAIN functional.  */
   9679   TREE_SET_CODE (obj, TREE_LIST);
   9680 #else
   9681   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
   9682 #endif
   9683 }
   9684 template <>
   9685 inline void
   9686 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
   9687 {
   9688   tree_common *c ATTRIBUTE_UNUSED = &obj->common;
   9689 
   9690 #ifdef ENABLE_GC_CHECKING
   9691   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
   9692   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
   9693   memset (obj, 0, sizeof (tree_list));
   9694 #endif
   9695 
   9696   /* Let valgrind know the entire object is available, but
   9697      uninitialized.  */
   9698   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
   9699 
   9700 #ifdef ENABLE_GC_CHECKING
   9701   TREE_SET_CODE (obj, TREE_LIST);
   9702 #else
   9703   TREE_CHAIN (obj) = NULL_TREE;
   9704   TREE_TYPE (obj) = NULL_TREE;
   9705 #endif
   9706   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (c, sizeof (*c)));
   9707 }
   9708 
   9709 /* Point to the first object in the TREE_LIST freelist.  */
   9710 static GTY((deletable)) tree tree_list_freelist_head;
   9711 /* Return the/an actual TREE_LIST freelist.  */
   9712 static inline freelist<tree_node>
   9713 tree_list_freelist ()
   9714 {
   9715   return tree_list_freelist_head;
   9716 }
   9717 
   9718 /* Point to the first object in the tinst_level freelist.  */
   9719 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
   9720 /* Return the/an actual tinst_level freelist.  */
   9721 static inline freelist<tinst_level>
   9722 tinst_level_freelist ()
   9723 {
   9724   return tinst_level_freelist_head;
   9725 }
   9726 
   9727 /* Point to the first object in the pending_template freelist.  */
   9728 static GTY((deletable)) pending_template *pending_template_freelist_head;
   9729 /* Return the/an actual pending_template freelist.  */
   9730 static inline freelist<pending_template>
   9731 pending_template_freelist ()
   9732 {
   9733   return pending_template_freelist_head;
   9734 }
   9735 
   9736 /* Build the TREE_LIST object out of a split list, store it
   9737    permanently, and return it.  */
   9738 tree
   9739 tinst_level::to_list ()
   9740 {
   9741   gcc_assert (split_list_p ());
   9742   tree ret = tree_list_freelist ().alloc ();
   9743   TREE_PURPOSE (ret) = tldcl;
   9744   TREE_VALUE (ret) = targs;
   9745   tldcl = ret;
   9746   targs = NULL;
   9747   gcc_assert (tree_list_p ());
   9748   return ret;
   9749 }
   9750 
   9751 const unsigned short tinst_level::refcount_infinity;
   9752 
   9753 /* Increment OBJ's refcount unless it is already infinite.  */
   9754 static tinst_level *
   9755 inc_refcount_use (tinst_level *obj)
   9756 {
   9757   if (obj && obj->refcount != tinst_level::refcount_infinity)
   9758     ++obj->refcount;
   9759   return obj;
   9760 }
   9761 
   9762 /* Release storage for OBJ and node, if it's a TREE_LIST.  */
   9763 void
   9764 tinst_level::free (tinst_level *obj)
   9765 {
   9766   if (obj->tree_list_p ())
   9767     tree_list_freelist ().free (obj->get_node ());
   9768   tinst_level_freelist ().free (obj);
   9769 }
   9770 
   9771 /* Decrement OBJ's refcount if not infinite.  If it reaches zero, release
   9772    OBJ's DECL and OBJ, and start over with the tinst_level object that
   9773    used to be referenced by OBJ's NEXT.  */
   9774 static void
   9775 dec_refcount_use (tinst_level *obj)
   9776 {
   9777   while (obj
   9778 	 && obj->refcount != tinst_level::refcount_infinity
   9779 	 && !--obj->refcount)
   9780     {
   9781       tinst_level *next = obj->next;
   9782       tinst_level::free (obj);
   9783       obj = next;
   9784     }
   9785 }
   9786 
   9787 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
   9788    and of the former PTR.  Omitting the second argument is equivalent
   9789    to passing (T*)NULL; this is allowed because passing the
   9790    zero-valued integral constant NULL confuses type deduction and/or
   9791    overload resolution.  */
   9792 template <typename T>
   9793 static void
   9794 set_refcount_ptr (T *& ptr, T *obj = NULL)
   9795 {
   9796   T *save = ptr;
   9797   ptr = inc_refcount_use (obj);
   9798   dec_refcount_use (save);
   9799 }
   9800 
   9801 static void
   9802 add_pending_template (tree d)
   9803 {
   9804   tree ti = (TYPE_P (d)
   9805 	     ? CLASSTYPE_TEMPLATE_INFO (d)
   9806 	     : DECL_TEMPLATE_INFO (d));
   9807   struct pending_template *pt;
   9808   int level;
   9809 
   9810   if (TI_PENDING_TEMPLATE_FLAG (ti))
   9811     return;
   9812 
   9813   /* We are called both from instantiate_decl, where we've already had a
   9814      tinst_level pushed, and instantiate_template, where we haven't.
   9815      Compensate.  */
   9816   gcc_assert (TREE_CODE (d) != TREE_LIST);
   9817   level = !current_tinst_level
   9818     || current_tinst_level->maybe_get_node () != d;
   9819 
   9820   if (level)
   9821     push_tinst_level (d);
   9822 
   9823   pt = pending_template_freelist ().alloc ();
   9824   pt->next = NULL;
   9825   pt->tinst = NULL;
   9826   set_refcount_ptr (pt->tinst, current_tinst_level);
   9827   if (last_pending_template)
   9828     last_pending_template->next = pt;
   9829   else
   9830     pending_templates = pt;
   9831 
   9832   last_pending_template = pt;
   9833 
   9834   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
   9835 
   9836   if (level)
   9837     pop_tinst_level ();
   9838 }
   9839 
   9840 
   9841 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
   9842    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
   9843    documentation for TEMPLATE_ID_EXPR.  */
   9844 
   9845 tree
   9846 lookup_template_function (tree fns, tree arglist)
   9847 {
   9848   if (fns == error_mark_node || arglist == error_mark_node)
   9849     return error_mark_node;
   9850 
   9851   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
   9852 
   9853   if (!is_overloaded_fn (fns) && !identifier_p (fns))
   9854     {
   9855       error ("%q#D is not a function template", fns);
   9856       return error_mark_node;
   9857     }
   9858 
   9859   if (BASELINK_P (fns))
   9860     {
   9861       fns = copy_node (fns);
   9862       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
   9863 					 unknown_type_node,
   9864 					 BASELINK_FUNCTIONS (fns),
   9865 					 arglist);
   9866       return fns;
   9867     }
   9868 
   9869   return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
   9870 }
   9871 
   9872 /* Within the scope of a template class S<T>, the name S gets bound
   9873    (in build_self_reference) to a TYPE_DECL for the class, not a
   9874    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
   9875    or one of its enclosing classes, and that type is a template,
   9876    return the associated TEMPLATE_DECL.  Otherwise, the original
   9877    DECL is returned.
   9878 
   9879    Also handle the case when DECL is a TREE_LIST of ambiguous
   9880    injected-class-names from different bases.  */
   9881 
   9882 tree
   9883 maybe_get_template_decl_from_type_decl (tree decl)
   9884 {
   9885   if (decl == NULL_TREE)
   9886     return decl;
   9887 
   9888   /* DR 176: A lookup that finds an injected-class-name (10.2
   9889      [class.member.lookup]) can result in an ambiguity in certain cases
   9890      (for example, if it is found in more than one base class). If all of
   9891      the injected-class-names that are found refer to specializations of
   9892      the same class template, and if the name is followed by a
   9893      template-argument-list, the reference refers to the class template
   9894      itself and not a specialization thereof, and is not ambiguous.  */
   9895   if (TREE_CODE (decl) == TREE_LIST)
   9896     {
   9897       tree t, tmpl = NULL_TREE;
   9898       for (t = decl; t; t = TREE_CHAIN (t))
   9899 	{
   9900 	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
   9901 	  if (!tmpl)
   9902 	    tmpl = elt;
   9903 	  else if (tmpl != elt)
   9904 	    break;
   9905 	}
   9906       if (tmpl && t == NULL_TREE)
   9907 	return tmpl;
   9908       else
   9909 	return decl;
   9910     }
   9911 
   9912   return (decl != NULL_TREE
   9913 	  && DECL_SELF_REFERENCE_P (decl)
   9914 	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
   9915     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
   9916 }
   9917 
   9918 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
   9919    parameters, find the desired type.
   9920 
   9921    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
   9922 
   9923    IN_DECL, if non-NULL, is the template declaration we are trying to
   9924    instantiate.
   9925 
   9926    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
   9927    the class we are looking up.
   9928 
   9929    Issue error and warning messages under control of COMPLAIN.
   9930 
   9931    If the template class is really a local class in a template
   9932    function, then the FUNCTION_CONTEXT is the function in which it is
   9933    being instantiated.
   9934 
   9935    ??? Note that this function is currently called *twice* for each
   9936    template-id: the first time from the parser, while creating the
   9937    incomplete type (finish_template_type), and the second type during the
   9938    real instantiation (instantiate_template_class). This is surely something
   9939    that we want to avoid. It also causes some problems with argument
   9940    coercion (see convert_nontype_argument for more information on this).  */
   9941 
   9942 tree
   9943 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
   9944 		       int entering_scope, tsubst_flags_t complain)
   9945 {
   9946   auto_timevar tv (TV_TEMPLATE_INST);
   9947 
   9948   tree templ = NULL_TREE, parmlist;
   9949   tree t;
   9950   spec_entry **slot;
   9951   spec_entry *entry;
   9952   spec_entry elt;
   9953   hashval_t hash;
   9954 
   9955   if (identifier_p (d1))
   9956     {
   9957       tree value = innermost_non_namespace_value (d1);
   9958       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
   9959 	templ = value;
   9960       else
   9961 	{
   9962 	  if (context)
   9963 	    push_decl_namespace (context);
   9964 	  templ = lookup_name (d1);
   9965 	  templ = maybe_get_template_decl_from_type_decl (templ);
   9966 	  if (context)
   9967 	    pop_decl_namespace ();
   9968 	}
   9969     }
   9970   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
   9971     {
   9972       tree type = TREE_TYPE (d1);
   9973 
   9974       /* If we are declaring a constructor, say A<T>::A<T>, we will get
   9975 	 an implicit typename for the second A.  Deal with it.  */
   9976       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
   9977 	type = TREE_TYPE (type);
   9978 
   9979       if (CLASSTYPE_TEMPLATE_INFO (type))
   9980 	{
   9981 	  templ = CLASSTYPE_TI_TEMPLATE (type);
   9982 	  d1 = DECL_NAME (templ);
   9983 	}
   9984     }
   9985   else if (TREE_CODE (d1) == ENUMERAL_TYPE
   9986 	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
   9987     {
   9988       templ = TYPE_TI_TEMPLATE (d1);
   9989       d1 = DECL_NAME (templ);
   9990     }
   9991   else if (DECL_TYPE_TEMPLATE_P (d1))
   9992     {
   9993       templ = d1;
   9994       d1 = DECL_NAME (templ);
   9995     }
   9996   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
   9997     {
   9998       templ = d1;
   9999       d1 = DECL_NAME (templ);
   10000     }
   10001 
   10002   /* Issue an error message if we didn't find a template.  */
   10003   if (! templ)
   10004     {
   10005       if (complain & tf_error)
   10006 	error ("%qT is not a template", d1);
   10007       return error_mark_node;
   10008     }
   10009 
   10010   if (TREE_CODE (templ) != TEMPLATE_DECL
   10011 	 /* Make sure it's a user visible template, if it was named by
   10012 	    the user.  */
   10013       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
   10014 	  && !PRIMARY_TEMPLATE_P (templ)))
   10015     {
   10016       if (complain & tf_error)
   10017 	{
   10018 	  error ("non-template type %qT used as a template", d1);
   10019 	  if (in_decl)
   10020 	    error ("for template declaration %q+D", in_decl);
   10021 	}
   10022       return error_mark_node;
   10023     }
   10024 
   10025   complain &= ~tf_user;
   10026 
   10027   /* An alias that just changes the name of a template is equivalent to the
   10028      other template, so if any of the arguments are pack expansions, strip
   10029      the alias to avoid problems with a pack expansion passed to a non-pack
   10030      alias template parameter (DR 1430).  */
   10031   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
   10032     templ = get_underlying_template (templ);
   10033 
   10034   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
   10035     {
   10036       tree parm;
   10037       tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
   10038       if (arglist2 == error_mark_node
   10039 	  || (!uses_template_parms (arglist2)
   10040 	      && check_instantiated_args (templ, arglist2, complain)))
   10041 	return error_mark_node;
   10042 
   10043       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
   10044       return parm;
   10045     }
   10046   else
   10047     {
   10048       tree template_type = TREE_TYPE (templ);
   10049       tree gen_tmpl;
   10050       tree type_decl;
   10051       tree found = NULL_TREE;
   10052       int arg_depth;
   10053       int parm_depth;
   10054       int is_dependent_type;
   10055       int use_partial_inst_tmpl = false;
   10056 
   10057       if (template_type == error_mark_node)
   10058 	/* An error occurred while building the template TEMPL, and a
   10059 	   diagnostic has most certainly been emitted for that
   10060 	   already.  Let's propagate that error.  */
   10061 	return error_mark_node;
   10062 
   10063       gen_tmpl = most_general_template (templ);
   10064       if (modules_p ())
   10065 	lazy_load_pendings (gen_tmpl);
   10066 
   10067       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
   10068       parm_depth = TMPL_PARMS_DEPTH (parmlist);
   10069       arg_depth = TMPL_ARGS_DEPTH (arglist);
   10070 
   10071       if (arg_depth == 1 && parm_depth > 1)
   10072 	{
   10073 	  /* We've been given an incomplete set of template arguments.
   10074 	     For example, given:
   10075 
   10076 	       template <class T> struct S1 {
   10077 		 template <class U> struct S2 {};
   10078 		 template <class U> struct S2<U*> {};
   10079 		};
   10080 
   10081 	     we will be called with an ARGLIST of `U*', but the
   10082 	     TEMPLATE will be `template <class T> template
   10083 	     <class U> struct S1<T>::S2'.  We must fill in the missing
   10084 	     arguments.  */
   10085 	  tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
   10086 	  arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
   10087 	  arg_depth = TMPL_ARGS_DEPTH (arglist);
   10088 	}
   10089 
   10090       /* Now we should have enough arguments.  */
   10091       gcc_assert (parm_depth == arg_depth);
   10092 
   10093       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
   10094 	{
   10095 	  /* The user referred to a specialization of an alias
   10096 	    template represented by GEN_TMPL.
   10097 
   10098 	    [temp.alias]/2 says:
   10099 
   10100 		When a template-id refers to the specialization of an
   10101 		alias template, it is equivalent to the associated
   10102 		type obtained by substitution of its
   10103 		template-arguments for the template-parameters in the
   10104 		type-id of the alias template.  */
   10105 
   10106 	  t = instantiate_alias_template (gen_tmpl, arglist, complain);
   10107 	  /* Note that the call above (by indirectly calling
   10108 	     register_specialization in tsubst_decl) registers the
   10109 	     TYPE_DECL representing the specialization of the alias
   10110 	     template.  So next time someone substitutes ARGLIST for
   10111 	     the template parms into the alias template (GEN_TMPL),
   10112 	     she'll get that TYPE_DECL back.  */
   10113 
   10114 	  if (t == error_mark_node)
   10115 	    return error_mark_node;
   10116 	  return TREE_TYPE (t);
   10117 	}
   10118 
   10119       /* From here on, we're only interested in the most general
   10120 	 template.  */
   10121 
   10122       /* Shortcut looking up the current class scope again.  */
   10123       for (tree cur = current_nonlambda_class_type ();
   10124 	   cur != NULL_TREE;
   10125 	   cur = get_containing_scope (cur))
   10126 	{
   10127 	  if (!CLASS_TYPE_P (cur))
   10128 	    continue;
   10129 
   10130 	  tree ti = CLASSTYPE_TEMPLATE_INFO (cur);
   10131 	  if (!ti || arg_depth > TMPL_ARGS_DEPTH (TI_ARGS (ti)))
   10132 	    break;
   10133 
   10134 	  if (gen_tmpl == most_general_template (TI_TEMPLATE (ti))
   10135 	      && comp_template_args (arglist, TI_ARGS (ti)))
   10136 	    return cur;
   10137 	}
   10138 
   10139       /* Calculate the BOUND_ARGS.  These will be the args that are
   10140 	 actually tsubst'd into the definition to create the
   10141 	 instantiation.  */
   10142       if (PRIMARY_TEMPLATE_P (gen_tmpl))
   10143 	arglist = coerce_template_parms (parmlist, arglist, gen_tmpl, complain);
   10144 
   10145       if (arglist == error_mark_node)
   10146 	/* We were unable to bind the arguments.  */
   10147 	return error_mark_node;
   10148 
   10149       /* In the scope of a template class, explicit references to the
   10150 	 template class refer to the type of the template, not any
   10151 	 instantiation of it.  For example, in:
   10152 
   10153 	   template <class T> class C { void f(C<T>); }
   10154 
   10155 	 the `C<T>' is just the same as `C'.  Outside of the
   10156 	 class, however, such a reference is an instantiation.  */
   10157       if (entering_scope
   10158 	  || !PRIMARY_TEMPLATE_P (gen_tmpl)
   10159 	  || currently_open_class (template_type))
   10160 	{
   10161 	  tree tinfo = TYPE_TEMPLATE_INFO (template_type);
   10162 
   10163 	  if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
   10164 	    return template_type;
   10165 	}
   10166 
   10167       /* If we already have this specialization, return it.  */
   10168       elt.tmpl = gen_tmpl;
   10169       elt.args = arglist;
   10170       elt.spec = NULL_TREE;
   10171       hash = spec_hasher::hash (&elt);
   10172       entry = type_specializations->find_with_hash (&elt, hash);
   10173 
   10174       if (entry)
   10175 	return entry->spec;
   10176 
   10177       /* If the template's constraints are not satisfied,
   10178          then we cannot form a valid type.
   10179 
   10180          Note that the check is deferred until after the hash
   10181          lookup. This prevents redundant checks on previously
   10182          instantiated specializations. */
   10183       if (flag_concepts
   10184 	  && !constraints_satisfied_p (gen_tmpl, arglist))
   10185         {
   10186           if (complain & tf_error)
   10187             {
   10188 	      auto_diagnostic_group d;
   10189               error ("template constraint failure for %qD", gen_tmpl);
   10190               diagnose_constraints (input_location, gen_tmpl, arglist);
   10191             }
   10192           return error_mark_node;
   10193         }
   10194 
   10195       is_dependent_type = uses_template_parms (arglist);
   10196 
   10197       /* If the deduced arguments are invalid, then the binding
   10198 	 failed.  */
   10199       if (!is_dependent_type
   10200 	  && check_instantiated_args (gen_tmpl,
   10201 				      INNERMOST_TEMPLATE_ARGS (arglist),
   10202 				      complain))
   10203 	return error_mark_node;
   10204 
   10205       if (!is_dependent_type
   10206 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
   10207 	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
   10208 	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
   10209 	/* This occurs when the user has tried to define a tagged type
   10210 	   in a scope that forbids it.  We emitted an error during the
   10211 	   parse.  We didn't complete the bail out then, so here we
   10212 	   are.  */
   10213 	return error_mark_node;
   10214 
   10215       context = DECL_CONTEXT (gen_tmpl);
   10216       if (context && TYPE_P (context))
   10217 	{
   10218 	  if (!uses_template_parms (DECL_CONTEXT (templ)))
   10219 	    /* If the context of the partially instantiated template is
   10220 	       already non-dependent, then we might as well use it.  */
   10221 	    context = DECL_CONTEXT (templ);
   10222 	  else
   10223 	    {
   10224 	      context = tsubst_aggr_type (context, arglist,
   10225 					  complain, in_decl, true);
   10226 	      /* Try completing the enclosing context if it's not already so.  */
   10227 	      if (context != error_mark_node
   10228 		  && !COMPLETE_TYPE_P (context))
   10229 		{
   10230 		  context = complete_type (context);
   10231 		  if (COMPLETE_TYPE_P (context))
   10232 		    {
   10233 		      /* Completion could have caused us to register the desired
   10234 			 specialization already, so check the table again.  */
   10235 		      entry = type_specializations->find_with_hash (&elt, hash);
   10236 		      if (entry)
   10237 			return entry->spec;
   10238 		    }
   10239 		}
   10240 	    }
   10241 	}
   10242       else
   10243 	context = tsubst (context, arglist, complain, in_decl);
   10244 
   10245       if (context == error_mark_node)
   10246 	return error_mark_node;
   10247 
   10248       if (!context)
   10249 	context = global_namespace;
   10250 
   10251       /* Create the type.  */
   10252       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
   10253 	{
   10254 	  if (!is_dependent_type)
   10255 	    {
   10256 	      set_current_access_from_decl (TYPE_NAME (template_type));
   10257 	      t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
   10258 			      tsubst (ENUM_UNDERLYING_TYPE (template_type),
   10259 				      arglist, complain, in_decl),
   10260 			      tsubst_attributes (TYPE_ATTRIBUTES (template_type),
   10261 						 arglist, complain, in_decl),
   10262 			      SCOPED_ENUM_P (template_type), NULL);
   10263 
   10264 	      if (t == error_mark_node)
   10265 		return t;
   10266 	    }
   10267 	  else
   10268             {
   10269               /* We don't want to call start_enum for this type, since
   10270                  the values for the enumeration constants may involve
   10271                  template parameters.  And, no one should be interested
   10272                  in the enumeration constants for such a type.  */
   10273               t = cxx_make_type (ENUMERAL_TYPE);
   10274               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
   10275             }
   10276           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
   10277 	  ENUM_FIXED_UNDERLYING_TYPE_P (t)
   10278 	    = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
   10279 	}
   10280       else if (CLASS_TYPE_P (template_type))
   10281 	{
   10282 	  /* Lambda closures are regenerated in tsubst_lambda_expr, not
   10283 	     instantiated here.  */
   10284 	  gcc_assert (!LAMBDA_TYPE_P (template_type));
   10285 
   10286 	  t = make_class_type (TREE_CODE (template_type));
   10287 	  CLASSTYPE_DECLARED_CLASS (t)
   10288 	    = CLASSTYPE_DECLARED_CLASS (template_type);
   10289 	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
   10290 
   10291 	  /* A local class.  Make sure the decl gets registered properly.  */
   10292 	  if (context == current_function_decl)
   10293 	    if (pushtag (DECL_NAME (gen_tmpl), t)
   10294 		== error_mark_node)
   10295 	      return error_mark_node;
   10296 
   10297 	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
   10298 	    /* This instantiation is another name for the primary
   10299 	       template type. Set the TYPE_CANONICAL field
   10300 	       appropriately. */
   10301 	    TYPE_CANONICAL (t) = template_type;
   10302 	  else if (any_template_arguments_need_structural_equality_p (arglist))
   10303 	    SET_TYPE_STRUCTURAL_EQUALITY (t);
   10304 	}
   10305       else
   10306 	gcc_unreachable ();
   10307 
   10308       /* If we called start_enum or pushtag above, this information
   10309 	 will already be set up.  */
   10310       type_decl = TYPE_NAME (t);
   10311       if (!type_decl)
   10312 	{
   10313 	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
   10314 
   10315 	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
   10316 	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
   10317 	  DECL_SOURCE_LOCATION (type_decl)
   10318 	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
   10319 	}
   10320 
   10321       set_instantiating_module (type_decl);
   10322       /* Although GEN_TMPL is the TEMPLATE_DECL, it has the same value
   10323 	 of export flag.  We want to propagate this because it might
   10324 	 be a friend declaration that pushes a new hidden binding.  */
   10325       DECL_MODULE_EXPORT_P (type_decl) = DECL_MODULE_EXPORT_P (gen_tmpl);
   10326 
   10327       if (CLASS_TYPE_P (template_type))
   10328 	{
   10329 	  TREE_PRIVATE (type_decl)
   10330 	    = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
   10331 	  TREE_PROTECTED (type_decl)
   10332 	    = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
   10333 	  if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
   10334 	    {
   10335 	      DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
   10336 	      DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
   10337 	    }
   10338 	}
   10339 
   10340       if (OVERLOAD_TYPE_P (t))
   10341 	{
   10342 	  static const char *tags[] = {"abi_tag", "may_alias"};
   10343 
   10344 	  for (unsigned ix = 0; ix != 2; ix++)
   10345 	    {
   10346 	      tree attributes
   10347 		= lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
   10348 
   10349 	      if (attributes)
   10350 		TYPE_ATTRIBUTES (t)
   10351 		  = tree_cons (TREE_PURPOSE (attributes),
   10352 			       TREE_VALUE (attributes),
   10353 			       TYPE_ATTRIBUTES (t));
   10354 	    }
   10355 	}
   10356 
   10357       /* Let's consider the explicit specialization of a member
   10358          of a class template specialization that is implicitly instantiated,
   10359 	 e.g.:
   10360 	     template<class T>
   10361 	     struct S
   10362 	     {
   10363 	       template<class U> struct M {}; //#0
   10364 	     };
   10365 
   10366 	     template<>
   10367 	     template<>
   10368 	     struct S<int>::M<char> //#1
   10369 	     {
   10370 	       int i;
   10371 	     };
   10372 	[temp.expl.spec]/4 says this is valid.
   10373 
   10374 	In this case, when we write:
   10375 	S<int>::M<char> m;
   10376 
   10377 	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
   10378 	the one of #0.
   10379 
   10380 	When we encounter #1, we want to store the partial instantiation
   10381 	of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
   10382 
   10383 	For all cases other than this "explicit specialization of member of a
   10384 	class template", we just want to store the most general template into
   10385 	the CLASSTYPE_TI_TEMPLATE of M.
   10386 
   10387 	This case of "explicit specialization of member of a class template"
   10388 	only happens when:
   10389 	1/ the enclosing class is an instantiation of, and therefore not
   10390 	the same as, the context of the most general template, and
   10391 	2/ we aren't looking at the partial instantiation itself, i.e.
   10392 	the innermost arguments are not the same as the innermost parms of
   10393 	the most general template.
   10394 
   10395 	So it's only when 1/ and 2/ happens that we want to use the partial
   10396 	instantiation of the member template in lieu of its most general
   10397 	template.  */
   10398 
   10399       if (PRIMARY_TEMPLATE_P (gen_tmpl)
   10400 	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
   10401 	  /* the enclosing class must be an instantiation...  */
   10402 	  && CLASS_TYPE_P (context)
   10403 	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
   10404 	{
   10405 	  TREE_VEC_LENGTH (arglist)--;
   10406 	  ++processing_template_decl;
   10407 	  tree tinfo = TYPE_TEMPLATE_INFO (TREE_TYPE (gen_tmpl));
   10408 	  tree partial_inst_args =
   10409 	    tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
   10410 		    arglist, complain, NULL_TREE);
   10411 	  --processing_template_decl;
   10412 	  TREE_VEC_LENGTH (arglist)++;
   10413 	  if (partial_inst_args == error_mark_node)
   10414 	    return error_mark_node;
   10415 	  use_partial_inst_tmpl =
   10416 	    /*...and we must not be looking at the partial instantiation
   10417 	     itself. */
   10418 	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
   10419 				 partial_inst_args);
   10420 	}
   10421 
   10422       if (!use_partial_inst_tmpl)
   10423 	/* This case is easy; there are no member templates involved.  */
   10424 	found = gen_tmpl;
   10425       else
   10426 	{
   10427 	  /* This is a full instantiation of a member template.  Find
   10428 	     the partial instantiation of which this is an instance.  */
   10429 
   10430 	  /* Temporarily reduce by one the number of levels in the ARGLIST
   10431 	     so as to avoid comparing the last set of arguments.  */
   10432 	  TREE_VEC_LENGTH (arglist)--;
   10433 	  /* We don't use COMPLAIN in the following call because this isn't
   10434 	     the immediate context of deduction.  For instance, tf_partial
   10435 	     could be set here as we might be at the beginning of template
   10436 	     argument deduction when any explicitly specified template
   10437 	     arguments are substituted into the function type.  tf_partial
   10438 	     could lead into trouble because we wouldn't find the partial
   10439 	     instantiation that might have been created outside tf_partial
   10440 	     context, because the levels of template parameters wouldn't
   10441 	     match, because in a tf_partial context, tsubst doesn't reduce
   10442 	     TEMPLATE_PARM_LEVEL.  */
   10443 	  found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
   10444 	  TREE_VEC_LENGTH (arglist)++;
   10445 	  found = (TREE_CODE (found) == TEMPLATE_DECL
   10446 		   ? found
   10447 		   : CLASSTYPE_TI_TEMPLATE (found));
   10448 
   10449 	  if (DECL_CLASS_TEMPLATE_P (found)
   10450 	      && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
   10451 	    {
   10452 	      /* If this partial instantiation is specialized, we want to
   10453 		 use it for hash table lookup.  */
   10454 	      elt.tmpl = found;
   10455 	      elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
   10456 	      hash = spec_hasher::hash (&elt);
   10457 	    }
   10458 	}
   10459 
   10460       /* Build template info for the new specialization.  */
   10461       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
   10462 
   10463       elt.spec = t;
   10464       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
   10465       gcc_checking_assert (*slot == NULL);
   10466       entry = ggc_alloc<spec_entry> ();
   10467       *entry = elt;
   10468       *slot = entry;
   10469 
   10470       /* Note this use of the partial instantiation so we can check it
   10471 	 later in maybe_process_partial_specialization.  */
   10472       DECL_TEMPLATE_INSTANTIATIONS (found)
   10473 	= tree_cons (arglist, t,
   10474 		     DECL_TEMPLATE_INSTANTIATIONS (found));
   10475 
   10476       if (TREE_CODE (template_type) == ENUMERAL_TYPE
   10477 	  && !uses_template_parms (current_nonlambda_scope ()))
   10478 	/* Now that the type has been registered on the instantiations
   10479 	   list, we set up the enumerators.  Because the enumeration
   10480 	   constants may involve the enumeration type itself, we make
   10481 	   sure to register the type first, and then create the
   10482 	   constants.  That way, doing tsubst_expr for the enumeration
   10483 	   constants won't result in recursive calls here; we'll find
   10484 	   the instantiation and exit above.  */
   10485 	tsubst_enum (template_type, t, arglist);
   10486 
   10487       if (CLASS_TYPE_P (template_type) && is_dependent_type)
   10488 	/* If the type makes use of template parameters, the
   10489 	   code that generates debugging information will crash.  */
   10490 	DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
   10491 
   10492       /* Possibly limit visibility based on template args.  */
   10493       TREE_PUBLIC (type_decl) = 1;
   10494       determine_visibility (type_decl);
   10495 
   10496       inherit_targ_abi_tags (t);
   10497 
   10498       return t;
   10499     }
   10500 }
   10501 
   10502 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
   10503 
   10504 tree
   10505 lookup_template_variable (tree templ, tree arglist, tsubst_flags_t complain)
   10506 {
   10507   if (flag_concepts && variable_concept_p (templ))
   10508     return build_concept_check (templ, arglist, tf_none);
   10509 
   10510   tree gen_templ = most_general_template (templ);
   10511   tree parms = DECL_INNERMOST_TEMPLATE_PARMS (gen_templ);
   10512   arglist = add_outermost_template_args (templ, arglist);
   10513   arglist = coerce_template_parms (parms, arglist, templ, complain);
   10514   if (arglist == error_mark_node)
   10515     return error_mark_node;
   10516 
   10517   /* The type of the expression is NULL_TREE since the template-id could refer
   10518      to an explicit or partial specialization. */
   10519   return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
   10520 }
   10521 
   10522 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR if it's
   10523    not dependent.  */
   10524 
   10525 tree
   10526 finish_template_variable (tree var, tsubst_flags_t complain)
   10527 {
   10528   tree templ = TREE_OPERAND (var, 0);
   10529   tree arglist = TREE_OPERAND (var, 1);
   10530 
   10531   /* If the template or arguments are dependent, then we
   10532      can't resolve the TEMPLATE_ID_EXPR yet.  */
   10533   if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (templ)) != 1
   10534       || any_dependent_template_arguments_p (arglist))
   10535     return var;
   10536 
   10537   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
   10538     {
   10539       if (complain & tf_error)
   10540 	{
   10541 	  auto_diagnostic_group d;
   10542 	  error ("use of invalid variable template %qE", var);
   10543 	  diagnose_constraints (location_of (var), templ, arglist);
   10544 	}
   10545       return error_mark_node;
   10546     }
   10547 
   10548   return instantiate_template (templ, arglist, complain);
   10549 }
   10550 
   10551 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
   10552    TARGS template args, and instantiate it if it's not dependent.  */
   10553 
   10554 tree
   10555 lookup_and_finish_template_variable (tree templ, tree targs,
   10556 				     tsubst_flags_t complain)
   10557 {
   10558   tree var = lookup_template_variable (templ, targs, complain);
   10559   if (var == error_mark_node)
   10560     return error_mark_node;
   10561   var = finish_template_variable (var, complain);
   10562   mark_used (var, complain);
   10563   return var;
   10564 }
   10565 
   10566 /* If the set of template parameters PARMS contains a template parameter
   10567    at the given LEVEL and INDEX, then return this parameter.  Otherwise
   10568    return NULL_TREE.  */
   10569 
   10570 static tree
   10571 corresponding_template_parameter_list (tree parms, int level, int index)
   10572 {
   10573   while (TMPL_PARMS_DEPTH (parms) > level)
   10574     parms = TREE_CHAIN (parms);
   10575 
   10576   if (TMPL_PARMS_DEPTH (parms) != level
   10577       || TREE_VEC_LENGTH (TREE_VALUE (parms)) <= index)
   10578     return NULL_TREE;
   10579 
   10580   return TREE_VEC_ELT (TREE_VALUE (parms), index);
   10581 }
   10582 
   10583 /* Return the TREE_LIST for the template parameter from PARMS that positionally
   10584    corresponds to the template parameter PARM, or else return NULL_TREE.  */
   10585 
   10586 static tree
   10587 corresponding_template_parameter_list (tree parms, tree parm)
   10588 {
   10589   int level, index;
   10590   template_parm_level_and_index (parm, &level, &index);
   10591   return corresponding_template_parameter_list (parms, level, index);
   10592 }
   10593 
   10594 /* As above, but pull out the actual parameter.  */
   10595 
   10596 static tree
   10597 corresponding_template_parameter (tree parms, tree parm)
   10598 {
   10599   tree list = corresponding_template_parameter_list (parms, parm);
   10600   if (!list)
   10601     return NULL_TREE;
   10602 
   10603   tree t = TREE_VALUE (list);
   10604   /* As in template_parm_to_arg.  */
   10605   if (TREE_CODE (t) == TYPE_DECL || TREE_CODE (t) == TEMPLATE_DECL)
   10606     t = TREE_TYPE (t);
   10607   else
   10608     t = DECL_INITIAL (t);
   10609 
   10610   gcc_assert (TEMPLATE_PARM_P (t));
   10611   return t;
   10612 }
   10613 
   10614 struct pair_fn_data
   10616 {
   10617   tree_fn_t fn;
   10618   tree_fn_t any_fn;
   10619   void *data;
   10620   /* True when we should also visit template parameters that occur in
   10621      non-deduced contexts.  */
   10622   bool include_nondeduced_p;
   10623   hash_set<tree> *visited;
   10624 };
   10625 
   10626 /* Called from for_each_template_parm via walk_tree.  */
   10627 
   10628 static tree
   10629 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
   10630 {
   10631   tree t = *tp;
   10632   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
   10633   tree_fn_t fn = pfd->fn;
   10634   void *data = pfd->data;
   10635   tree result = NULL_TREE;
   10636 
   10637 #define WALK_SUBTREE(NODE)						\
   10638   do									\
   10639     {									\
   10640       result = for_each_template_parm (NODE, fn, data, pfd->visited,	\
   10641 				       pfd->include_nondeduced_p,	\
   10642 				       pfd->any_fn);			\
   10643       if (result) goto out;						\
   10644     }									\
   10645   while (0)
   10646 
   10647   if (pfd->any_fn && (*pfd->any_fn)(t, data))
   10648     return t;
   10649 
   10650   if (TYPE_P (t)
   10651       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
   10652     WALK_SUBTREE (TYPE_CONTEXT (t));
   10653 
   10654   switch (TREE_CODE (t))
   10655     {
   10656     case RECORD_TYPE:
   10657       if (TYPE_PTRMEMFUNC_P (t))
   10658 	break;
   10659       /* Fall through.  */
   10660 
   10661     case UNION_TYPE:
   10662     case ENUMERAL_TYPE:
   10663       if (!TYPE_TEMPLATE_INFO (t))
   10664 	*walk_subtrees = 0;
   10665       else
   10666 	WALK_SUBTREE (TYPE_TI_ARGS (t));
   10667       break;
   10668 
   10669     case INTEGER_TYPE:
   10670       WALK_SUBTREE (TYPE_MIN_VALUE (t));
   10671       WALK_SUBTREE (TYPE_MAX_VALUE (t));
   10672       break;
   10673 
   10674     case METHOD_TYPE:
   10675       /* Since we're not going to walk subtrees, we have to do this
   10676 	 explicitly here.  */
   10677       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
   10678       /* Fall through.  */
   10679 
   10680     case FUNCTION_TYPE:
   10681       /* Check the return type.  */
   10682       WALK_SUBTREE (TREE_TYPE (t));
   10683 
   10684       /* Check the parameter types.  Since default arguments are not
   10685 	 instantiated until they are needed, the TYPE_ARG_TYPES may
   10686 	 contain expressions that involve template parameters.  But,
   10687 	 no-one should be looking at them yet.  And, once they're
   10688 	 instantiated, they don't contain template parameters, so
   10689 	 there's no point in looking at them then, either.  */
   10690       {
   10691 	tree parm;
   10692 
   10693 	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
   10694 	  WALK_SUBTREE (TREE_VALUE (parm));
   10695 
   10696 	/* Since we've already handled the TYPE_ARG_TYPES, we don't
   10697 	   want walk_tree walking into them itself.  */
   10698 	*walk_subtrees = 0;
   10699       }
   10700 
   10701       if (flag_noexcept_type)
   10702 	{
   10703 	  tree spec = TYPE_RAISES_EXCEPTIONS (t);
   10704 	  if (spec)
   10705 	    WALK_SUBTREE (TREE_PURPOSE (spec));
   10706 	}
   10707       break;
   10708 
   10709     case TYPEOF_TYPE:
   10710     case DECLTYPE_TYPE:
   10711       if (pfd->include_nondeduced_p
   10712 	  && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
   10713 				     pfd->visited,
   10714 				     pfd->include_nondeduced_p,
   10715 				     pfd->any_fn))
   10716 	return error_mark_node;
   10717       *walk_subtrees = false;
   10718       break;
   10719 
   10720     case TRAIT_TYPE:
   10721       if (pfd->include_nondeduced_p)
   10722 	{
   10723 	  WALK_SUBTREE (TRAIT_TYPE_TYPE1 (t));
   10724 	  WALK_SUBTREE (TRAIT_TYPE_TYPE2 (t));
   10725 	}
   10726       *walk_subtrees = false;
   10727       break;
   10728 
   10729     case FUNCTION_DECL:
   10730     case VAR_DECL:
   10731       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
   10732 	WALK_SUBTREE (DECL_TI_ARGS (t));
   10733       break;
   10734 
   10735     case PARM_DECL:
   10736       WALK_SUBTREE (TREE_TYPE (t));
   10737       break;
   10738 
   10739     case CONST_DECL:
   10740       if (DECL_TEMPLATE_PARM_P (t))
   10741 	WALK_SUBTREE (DECL_INITIAL (t));
   10742       if (DECL_CONTEXT (t)
   10743 	  && pfd->include_nondeduced_p)
   10744 	WALK_SUBTREE (DECL_CONTEXT (t));
   10745       break;
   10746 
   10747     case BOUND_TEMPLATE_TEMPLATE_PARM:
   10748       /* Record template parameters such as `T' inside `TT<T>'.  */
   10749       WALK_SUBTREE (TYPE_TI_ARGS (t));
   10750       /* Fall through.  */
   10751 
   10752     case TEMPLATE_TEMPLATE_PARM:
   10753     case TEMPLATE_TYPE_PARM:
   10754     case TEMPLATE_PARM_INDEX:
   10755       if (fn && (*fn)(t, data))
   10756 	return t;
   10757       else if (!fn)
   10758 	return t;
   10759       break;
   10760 
   10761     case TEMPLATE_DECL:
   10762       /* A template template parameter is encountered.  */
   10763       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
   10764 	WALK_SUBTREE (TREE_TYPE (t));
   10765 
   10766       /* Already substituted template template parameter */
   10767       *walk_subtrees = 0;
   10768       break;
   10769 
   10770     case TYPENAME_TYPE:
   10771       /* A template-id in a TYPENAME_TYPE might be a deduced context after
   10772 	 partial instantiation.  */
   10773       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
   10774       *walk_subtrees = 0;
   10775       break;
   10776 
   10777     case INDIRECT_REF:
   10778     case COMPONENT_REF:
   10779       /* If there's no type, then this thing must be some expression
   10780 	 involving template parameters.  */
   10781       if (!fn && !TREE_TYPE (t))
   10782 	return error_mark_node;
   10783       break;
   10784 
   10785     case CONSTRUCTOR:
   10786     case TRAIT_EXPR:
   10787     case PLUS_EXPR:
   10788     case MULT_EXPR:
   10789     case SCOPE_REF:
   10790       /* These are non-deduced contexts.  */
   10791       if (!pfd->include_nondeduced_p)
   10792 	*walk_subtrees = 0;
   10793       break;
   10794 
   10795     case MODOP_EXPR:
   10796     case CAST_EXPR:
   10797     case IMPLICIT_CONV_EXPR:
   10798     case REINTERPRET_CAST_EXPR:
   10799     case CONST_CAST_EXPR:
   10800     case STATIC_CAST_EXPR:
   10801     case DYNAMIC_CAST_EXPR:
   10802     case ARROW_EXPR:
   10803     case DOTSTAR_EXPR:
   10804     case TYPEID_EXPR:
   10805     case PSEUDO_DTOR_EXPR:
   10806       if (!fn)
   10807 	return error_mark_node;
   10808       break;
   10809 
   10810     default:
   10811       break;
   10812     }
   10813 
   10814   #undef WALK_SUBTREE
   10815 
   10816   /* We didn't find any template parameters we liked.  */
   10817  out:
   10818   return result;
   10819 }
   10820 
   10821 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
   10822    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
   10823    call FN with the parameter and the DATA.
   10824    If FN returns nonzero, the iteration is terminated, and
   10825    for_each_template_parm returns 1.  Otherwise, the iteration
   10826    continues.  If FN never returns a nonzero value, the value
   10827    returned by for_each_template_parm is 0.  If FN is NULL, it is
   10828    considered to be the function which always returns 1.
   10829 
   10830    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
   10831    parameters that occur in non-deduced contexts.  When false, only
   10832    visits those template parameters that can be deduced.  */
   10833 
   10834 static tree
   10835 for_each_template_parm (tree t, tree_fn_t fn, void* data,
   10836 			hash_set<tree> *visited,
   10837 			bool include_nondeduced_p,
   10838 			tree_fn_t any_fn)
   10839 {
   10840   struct pair_fn_data pfd;
   10841   tree result;
   10842 
   10843   /* Set up.  */
   10844   pfd.fn = fn;
   10845   pfd.any_fn = any_fn;
   10846   pfd.data = data;
   10847   pfd.include_nondeduced_p = include_nondeduced_p;
   10848 
   10849   /* Walk the tree.  (Conceptually, we would like to walk without
   10850      duplicates, but for_each_template_parm_r recursively calls
   10851      for_each_template_parm, so we would need to reorganize a fair
   10852      bit to use walk_tree_without_duplicates, so we keep our own
   10853      visited list.)  */
   10854   if (visited)
   10855     pfd.visited = visited;
   10856   else
   10857     pfd.visited = new hash_set<tree>;
   10858   result = cp_walk_tree (&t,
   10859 		         for_each_template_parm_r,
   10860 		         &pfd,
   10861 		         pfd.visited);
   10862 
   10863   /* Clean up.  */
   10864   if (!visited)
   10865     {
   10866       delete pfd.visited;
   10867       pfd.visited = 0;
   10868     }
   10869 
   10870   return result;
   10871 }
   10872 
   10873 struct find_template_parameter_info
   10874 {
   10875   explicit find_template_parameter_info (tree ctx_parms)
   10876     : ctx_parms (ctx_parms),
   10877       max_depth (TMPL_PARMS_DEPTH (ctx_parms))
   10878   {}
   10879 
   10880   hash_set<tree> visited;
   10881   hash_set<tree> parms;
   10882   tree parm_list = NULL_TREE;
   10883   tree *parm_list_tail = &parm_list;
   10884   tree ctx_parms;
   10885   int max_depth;
   10886 
   10887   tree find_in (tree);
   10888   tree find_in_recursive (tree);
   10889   bool found (tree);
   10890   unsigned num_found () { return parms.elements (); }
   10891 };
   10892 
   10893 /* Appends the declaration of T to the list in DATA.  */
   10894 
   10895 static int
   10896 keep_template_parm (tree t, void* data)
   10897 {
   10898   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
   10899 
   10900   /* Template parameters declared within the expression are not part of
   10901      the parameter mapping. For example, in this concept:
   10902 
   10903        template<typename T>
   10904        concept C = requires { <expr> } -> same_as<int>;
   10905 
   10906      the return specifier same_as<int> declares a new decltype parameter
   10907      that must not be part of the parameter mapping. The same is true
   10908      for generic lambda parameters, lambda template parameters, etc.  */
   10909   int level;
   10910   int index;
   10911   template_parm_level_and_index (t, &level, &index);
   10912   if (level == 0 || level > ftpi->max_depth)
   10913     return 0;
   10914 
   10915   if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
   10916     /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
   10917        BOUND_TEMPLATE_TEMPLATE_PARM itself.  */
   10918     t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
   10919 
   10920   /* This template parameter might be an argument to a cached dependent
   10921      specalization that was formed earlier inside some other template, in
   10922      which case the parameter is not among the ones that are in-scope.
   10923      Look in CTX_PARMS to find the corresponding in-scope template
   10924      parameter, and use it instead.  */
   10925   if (tree in_scope = corresponding_template_parameter (ftpi->ctx_parms, t))
   10926     t = in_scope;
   10927 
   10928   /* Arguments like const T yield parameters like const T. This means that
   10929      a template-id like X<T, const T> would yield two distinct parameters:
   10930      T and const T. Adjust types to their unqualified versions.  */
   10931   if (TYPE_P (t))
   10932     t = TYPE_MAIN_VARIANT (t);
   10933   if (!ftpi->parms.add (t))
   10934     {
   10935       /* Append T to PARM_LIST.  */
   10936       tree node = build_tree_list (NULL_TREE, t);
   10937       *ftpi->parm_list_tail = node;
   10938       ftpi->parm_list_tail = &TREE_CHAIN (node);
   10939     }
   10940 
   10941   /* Verify the parameter we found has a valid index.  */
   10942   if (flag_checking)
   10943     {
   10944       tree parms = ftpi->ctx_parms;
   10945       while (TMPL_PARMS_DEPTH (parms) > level)
   10946 	parms = TREE_CHAIN (parms);
   10947       if (int len = TREE_VEC_LENGTH (TREE_VALUE (parms)))
   10948 	gcc_assert (index < len);
   10949     }
   10950 
   10951   return 0;
   10952 }
   10953 
   10954 /* Ensure that we recursively examine certain terms that are not normally
   10955    visited in for_each_template_parm_r.  */
   10956 
   10957 static int
   10958 any_template_parm_r (tree t, void *data)
   10959 {
   10960   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
   10961 
   10962 #define WALK_SUBTREE(NODE)						\
   10963   do									\
   10964     {									\
   10965       for_each_template_parm (NODE, keep_template_parm, data,		\
   10966 			      &ftpi->visited, true,			\
   10967 			      any_template_parm_r);			\
   10968     }									\
   10969   while (0)
   10970 
   10971   /* A mention of a member alias/typedef is a use of all of its template
   10972      arguments, including those from the enclosing class, so we don't use
   10973      alias_template_specialization_p here.  */
   10974   if (TYPE_P (t) && typedef_variant_p (t))
   10975     if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
   10976       WALK_SUBTREE (TI_ARGS (tinfo));
   10977 
   10978   switch (TREE_CODE (t))
   10979     {
   10980     case TEMPLATE_TYPE_PARM:
   10981       /* Type constraints of a placeholder type may contain parameters.  */
   10982       if (is_auto (t))
   10983 	if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
   10984 	  WALK_SUBTREE (constr);
   10985       break;
   10986 
   10987     case TEMPLATE_ID_EXPR:
   10988       /* Search through references to variable templates.  */
   10989       WALK_SUBTREE (TREE_OPERAND (t, 0));
   10990       WALK_SUBTREE (TREE_OPERAND (t, 1));
   10991       break;
   10992 
   10993     case TEMPLATE_PARM_INDEX:
   10994       /* No need to consider template parameters within the type of an NTTP:
   10995 	 substitution into an NTTP is done directly with the corresponding
   10996 	 template argument, and its type only comes into play earlier during
   10997 	 coercion.  */
   10998       break;
   10999 
   11000     case TEMPLATE_DECL:
   11001       /* If T is a member template that shares template parameters with
   11002 	 ctx_parms, we need to mark all those parameters for mapping.
   11003 	 To that end, it should suffice to just walk the DECL_CONTEXT of
   11004 	 the template (assuming the template is not overly general).  */
   11005       WALK_SUBTREE (DECL_CONTEXT (t));
   11006       break;
   11007 
   11008     case LAMBDA_EXPR:
   11009       {
   11010 	/* Look in the parms and body.  */
   11011 	tree fn = lambda_function (t);
   11012 	WALK_SUBTREE (TREE_TYPE (fn));
   11013 	WALK_SUBTREE (DECL_SAVED_TREE (fn));
   11014       }
   11015       break;
   11016 
   11017     case IDENTIFIER_NODE:
   11018       if (IDENTIFIER_CONV_OP_P (t))
   11019 	/* The conversion-type-id of a conversion operator may be dependent.  */
   11020 	WALK_SUBTREE (TREE_TYPE (t));
   11021       break;
   11022 
   11023     case CONVERT_EXPR:
   11024       if (is_dummy_object (t))
   11025 	WALK_SUBTREE (TREE_TYPE (t));
   11026       break;
   11027 
   11028     default:
   11029       break;
   11030     }
   11031 
   11032   /* Keep walking.  */
   11033   return 0;
   11034 }
   11035 
   11036 /* Look through T for template parameters.  */
   11037 
   11038 tree
   11039 find_template_parameter_info::find_in (tree t)
   11040 {
   11041   return for_each_template_parm (t, keep_template_parm, this, &visited,
   11042 				 /*include_nondeduced*/true,
   11043 				 any_template_parm_r);
   11044 }
   11045 
   11046 /* As above, but also recursively look into the default arguments of template
   11047    parameters we found.  Used for alias CTAD.  */
   11048 
   11049 tree
   11050 find_template_parameter_info::find_in_recursive (tree t)
   11051 {
   11052   if (tree r = find_in (t))
   11053     return r;
   11054   /* Since newly found parms are added to the end of the list, we
   11055      can just walk it until we reach the end.  */
   11056   for (tree pl = parm_list; pl; pl = TREE_CHAIN (pl))
   11057     {
   11058       tree parm = TREE_VALUE (pl);
   11059       tree list = corresponding_template_parameter_list (ctx_parms, parm);
   11060       if (tree r = find_in (TREE_PURPOSE (list)))
   11061 	return r;
   11062     }
   11063   return NULL_TREE;
   11064 }
   11065 
   11066 /* True if PARM was found by a previous call to find_in.  PARM can be a
   11067    TREE_LIST, a DECL_TEMPLATE_PARM_P, or a TEMPLATE_PARM_P.  */
   11068 
   11069 bool
   11070 find_template_parameter_info::found (tree parm)
   11071 {
   11072   if (TREE_CODE (parm) == TREE_LIST)
   11073     parm = TREE_VALUE (parm);
   11074   if (TREE_CODE (parm) == TYPE_DECL
   11075       || TREE_CODE (parm) == TEMPLATE_DECL)
   11076     parm = TREE_TYPE (parm);
   11077   else
   11078     parm = DECL_INITIAL (parm);
   11079   gcc_checking_assert (TEMPLATE_PARM_P (parm));
   11080   return parms.contains (parm);
   11081 }
   11082 
   11083 /* Returns a list of unique template parameters found within T, where CTX_PARMS
   11084    are the template parameters in scope.  */
   11085 
   11086 tree
   11087 find_template_parameters (tree t, tree ctx_parms)
   11088 {
   11089   if (!ctx_parms)
   11090     return NULL_TREE;
   11091 
   11092   find_template_parameter_info ftpi (ctx_parms);
   11093   ftpi.find_in (t);
   11094   return ftpi.parm_list;
   11095 }
   11096 
   11097 /* Returns true if T depends on any template parameter.  */
   11098 
   11099 bool
   11100 uses_template_parms (tree t)
   11101 {
   11102   if (t == NULL_TREE || t == error_mark_node)
   11103     return false;
   11104 
   11105   /* Namespaces can't depend on any template parameters.  */
   11106   if (TREE_CODE (t) == NAMESPACE_DECL)
   11107     return false;
   11108 
   11109   processing_template_decl_sentinel ptds (/*reset*/false);
   11110   ++processing_template_decl;
   11111 
   11112   if (TYPE_P (t))
   11113     return dependent_type_p (t);
   11114   else if (TREE_CODE (t) == TREE_VEC)
   11115     return any_dependent_template_arguments_p (t);
   11116   else if (TREE_CODE (t) == TREE_LIST)
   11117     return (uses_template_parms (TREE_VALUE (t))
   11118 	    || uses_template_parms (TREE_CHAIN (t)));
   11119   else if (TREE_CODE (t) == TYPE_DECL)
   11120     return dependent_type_p (TREE_TYPE (t));
   11121   else
   11122     return instantiation_dependent_expression_p (t);
   11123 }
   11124 
   11125 /* Returns true if T depends on any template parameter with level LEVEL.  */
   11126 
   11127 bool
   11128 uses_template_parms_level (tree t, int level)
   11129 {
   11130   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
   11131 				 /*include_nondeduced_p=*/true);
   11132 }
   11133 
   11134 /* Returns true if the signature of DECL depends on any template parameter from
   11135    its enclosing class.  */
   11136 
   11137 static bool
   11138 uses_outer_template_parms (tree decl)
   11139 {
   11140   int depth;
   11141   if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
   11142     depth = TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl)) - 1;
   11143   else
   11144     depth = template_class_depth (CP_DECL_CONTEXT (decl));
   11145   if (depth == 0)
   11146     return false;
   11147   if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
   11148 			      &depth, NULL, /*include_nondeduced_p=*/true))
   11149     return true;
   11150   if (PRIMARY_TEMPLATE_P (decl)
   11151       || DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
   11152     {
   11153       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (decl));
   11154       for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
   11155 	{
   11156 	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
   11157 	  tree defarg = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
   11158 	  if (TREE_CODE (parm) == PARM_DECL
   11159 	      && for_each_template_parm (TREE_TYPE (parm),
   11160 					 template_parm_outer_level,
   11161 					 &depth, NULL, /*nondeduced*/true))
   11162 	    return true;
   11163 	  if (TREE_CODE (parm) == TEMPLATE_DECL
   11164 	      && uses_outer_template_parms (parm))
   11165 	    return true;
   11166 	  if (defarg
   11167 	      && for_each_template_parm (defarg, template_parm_outer_level,
   11168 					 &depth, NULL, /*nondeduced*/true))
   11169 	    return true;
   11170 	}
   11171     }
   11172   if (uses_outer_template_parms_in_constraints (decl))
   11173     return true;
   11174   return false;
   11175 }
   11176 
   11177 /* Returns true if the constraints of DECL depend on any template parameters
   11178    from its enclosing scope.  */
   11179 
   11180 bool
   11181 uses_outer_template_parms_in_constraints (tree decl, tree ctx/*=NULL_TREE*/)
   11182 {
   11183   tree ci = get_constraints (decl);
   11184   if (ci)
   11185     ci = CI_ASSOCIATED_CONSTRAINTS (ci);
   11186   if (!ci)
   11187     return false;
   11188   if (!ctx)
   11189     {
   11190       if (tree fc = DECL_FRIEND_CONTEXT (decl))
   11191 	ctx = fc;
   11192       else
   11193 	ctx = CP_DECL_CONTEXT (decl);
   11194     }
   11195   int depth = template_class_depth (ctx);
   11196   if (depth == 0)
   11197     return false;
   11198   return for_each_template_parm (ci, template_parm_outer_level,
   11199 				 &depth, NULL, /*nondeduced*/true);
   11200 }
   11201 
   11202 /* Returns TRUE iff INST is an instantiation we don't need to do in an
   11203    ill-formed translation unit, i.e. a variable or function that isn't
   11204    usable in a constant expression.  */
   11205 
   11206 static inline bool
   11207 neglectable_inst_p (tree d)
   11208 {
   11209   return (d && DECL_P (d)
   11210 	  && !undeduced_auto_decl (d)
   11211 	  && !(TREE_CODE (d) == FUNCTION_DECL
   11212 	       ? FNDECL_MANIFESTLY_CONST_EVALUATED (d)
   11213 	       : decl_maybe_constant_var_p (d)));
   11214 }
   11215 
   11216 /* Returns TRUE iff we should refuse to instantiate DECL because it's
   11217    neglectable and instantiated from within an erroneous instantiation.  */
   11218 
   11219 static bool
   11220 limit_bad_template_recursion (tree decl)
   11221 {
   11222   struct tinst_level *lev = current_tinst_level;
   11223   int errs = errorcount + sorrycount;
   11224   if (errs == 0 || !neglectable_inst_p (decl))
   11225     return false;
   11226 
   11227   /* Avoid instantiating members of an ill-formed class.  */
   11228   bool refuse
   11229     = (DECL_CLASS_SCOPE_P (decl)
   11230        && CLASSTYPE_ERRONEOUS (DECL_CONTEXT (decl)));
   11231 
   11232   if (!refuse)
   11233     {
   11234       for (; lev; lev = lev->next)
   11235 	if (neglectable_inst_p (lev->maybe_get_node ()))
   11236 	  break;
   11237       refuse = (lev && errs > lev->errors);
   11238     }
   11239 
   11240   if (refuse)
   11241     {
   11242       /* Don't warn about it not being defined.  */
   11243       suppress_warning (decl, OPT_Wunused);
   11244       tree clone;
   11245       FOR_EACH_CLONE (clone, decl)
   11246 	suppress_warning (clone, OPT_Wunused);
   11247     }
   11248   return refuse;
   11249 }
   11250 
   11251 static int tinst_depth;
   11252 extern int max_tinst_depth;
   11253 int depth_reached;
   11254 
   11255 static GTY(()) struct tinst_level *last_error_tinst_level;
   11256 
   11257 /* We're starting to instantiate D; record the template instantiation context
   11258    at LOC for diagnostics and to restore it later.  */
   11259 
   11260 bool
   11261 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
   11262 {
   11263   struct tinst_level *new_level;
   11264 
   11265   if (tinst_depth >= max_tinst_depth)
   11266     {
   11267       /* Tell error.cc not to try to instantiate any templates.  */
   11268       at_eof = 3;
   11269       fatal_error (input_location,
   11270 		   "template instantiation depth exceeds maximum of %d"
   11271 		   " (use %<-ftemplate-depth=%> to increase the maximum)",
   11272                    max_tinst_depth);
   11273       return false;
   11274     }
   11275 
   11276   /* If the current instantiation caused problems, don't let it instantiate
   11277      anything else.  Do allow deduction substitution and decls usable in
   11278      constant expressions.  */
   11279   if (!targs && limit_bad_template_recursion (tldcl))
   11280     {
   11281       /* Avoid no_linkage_errors and unused function (and all other)
   11282 	 warnings for this decl.  */
   11283       suppress_warning (tldcl);
   11284       return false;
   11285     }
   11286 
   11287   /* When not -quiet, dump template instantiations other than functions, since
   11288      announce_function will take care of those.  */
   11289   if (!quiet_flag && !targs
   11290       && TREE_CODE (tldcl) != TREE_LIST
   11291       && TREE_CODE (tldcl) != FUNCTION_DECL)
   11292     fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
   11293 
   11294   new_level = tinst_level_freelist ().alloc ();
   11295   new_level->tldcl = tldcl;
   11296   new_level->targs = targs;
   11297   new_level->locus = loc;
   11298   new_level->errors = errorcount + sorrycount;
   11299   new_level->next = NULL;
   11300   new_level->refcount = 0;
   11301   new_level->path = new_level->visible = nullptr;
   11302   set_refcount_ptr (new_level->next, current_tinst_level);
   11303   set_refcount_ptr (current_tinst_level, new_level);
   11304 
   11305   ++tinst_depth;
   11306   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
   11307     depth_reached = tinst_depth;
   11308 
   11309   return true;
   11310 }
   11311 
   11312 /* We're starting substitution of TMPL<ARGS>; record the template
   11313    substitution context for diagnostics and to restore it later.  */
   11314 
   11315 bool
   11316 push_tinst_level (tree tmpl, tree args)
   11317 {
   11318   return push_tinst_level_loc (tmpl, args, input_location);
   11319 }
   11320 
   11321 /* We're starting to instantiate D; record INPUT_LOCATION and the
   11322    template instantiation context for diagnostics and to restore it
   11323    later.  */
   11324 
   11325 bool
   11326 push_tinst_level (tree d)
   11327 {
   11328   return push_tinst_level_loc (d, input_location);
   11329 }
   11330 
   11331 /* Likewise, but record LOC as the program location.  */
   11332 
   11333 bool
   11334 push_tinst_level_loc (tree d, location_t loc)
   11335 {
   11336   gcc_assert (TREE_CODE (d) != TREE_LIST);
   11337   return push_tinst_level_loc (d, NULL, loc);
   11338 }
   11339 
   11340 /* We're done instantiating this template; return to the instantiation
   11341    context.  */
   11342 
   11343 void
   11344 pop_tinst_level (void)
   11345 {
   11346   /* Restore the filename and line number stashed away when we started
   11347      this instantiation.  */
   11348   input_location = current_tinst_level->locus;
   11349   set_refcount_ptr (current_tinst_level, current_tinst_level->next);
   11350   --tinst_depth;
   11351 }
   11352 
   11353 /* We're instantiating a deferred template; restore the template
   11354    instantiation context in which the instantiation was requested, which
   11355    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
   11356 
   11357 static tree
   11358 reopen_tinst_level (struct tinst_level *level)
   11359 {
   11360   struct tinst_level *t;
   11361 
   11362   tinst_depth = 0;
   11363   for (t = level; t; t = t->next)
   11364     ++tinst_depth;
   11365 
   11366   set_refcount_ptr (current_tinst_level, level);
   11367   pop_tinst_level ();
   11368   if (current_tinst_level)
   11369     current_tinst_level->errors = errorcount+sorrycount;
   11370   return level->maybe_get_node ();
   11371 }
   11372 
   11373 /* Returns the TINST_LEVEL which gives the original instantiation
   11374    context.  */
   11375 
   11376 struct tinst_level *
   11377 outermost_tinst_level (void)
   11378 {
   11379   struct tinst_level *level = current_tinst_level;
   11380   if (level)
   11381     while (level->next)
   11382       level = level->next;
   11383   return level;
   11384 }
   11385 
   11386 /* True iff T is a friend function declaration that is not itself a template
   11387    and is not defined in a class template.  */
   11388 
   11389 bool
   11390 non_templated_friend_p (tree t)
   11391 {
   11392   if (t && TREE_CODE (t) == FUNCTION_DECL
   11393       && DECL_UNIQUE_FRIEND_P (t))
   11394     {
   11395       tree ti = DECL_TEMPLATE_INFO (t);
   11396       if (!ti)
   11397 	return true;
   11398       /* DECL_FRIEND_CONTEXT is set for a friend defined in class.  */
   11399       if (DECL_FRIEND_CONTEXT (t))
   11400 	return false;
   11401       /* Non-templated friends in a class template are still represented with a
   11402 	 TEMPLATE_DECL; check that its primary template is the befriending
   11403 	 class.  Note that DECL_PRIMARY_TEMPLATE is null for
   11404 	 template <class T> friend A<T>::f(); */
   11405       tree tmpl = TI_TEMPLATE (ti);
   11406       tree primary = DECL_PRIMARY_TEMPLATE (tmpl);
   11407       return (primary && primary != tmpl);
   11408     }
   11409   else
   11410     return false;
   11411 }
   11412 
   11413 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
   11414    vector of template arguments, as for tsubst.
   11415 
   11416    Returns an appropriate tsubst'd friend declaration.  */
   11417 
   11418 static tree
   11419 tsubst_friend_function (tree decl, tree args)
   11420 {
   11421   tree new_friend;
   11422 
   11423   if (TREE_CODE (decl) == FUNCTION_DECL
   11424       && DECL_TEMPLATE_INSTANTIATION (decl)
   11425       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
   11426     /* This was a friend declared with an explicit template
   11427        argument list, e.g.:
   11428 
   11429        friend void f<>(T);
   11430 
   11431        to indicate that f was a template instantiation, not a new
   11432        function declaration.  Now, we have to figure out what
   11433        instantiation of what template.  */
   11434     {
   11435       tree template_id, arglist, fns;
   11436       tree new_args;
   11437       tree tmpl;
   11438       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
   11439 
   11440       /* Friend functions are looked up in the containing namespace scope.
   11441 	 We must enter that scope, to avoid finding member functions of the
   11442 	 current class with same name.  */
   11443       push_nested_namespace (ns);
   11444       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
   11445 			 tf_warning_or_error, NULL_TREE);
   11446       pop_nested_namespace (ns);
   11447       arglist = tsubst (DECL_TI_ARGS (decl), args,
   11448 			tf_warning_or_error, NULL_TREE);
   11449       template_id = lookup_template_function (fns, arglist);
   11450 
   11451       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
   11452       tmpl = determine_specialization (template_id, new_friend,
   11453 				       &new_args,
   11454 				       /*need_member_template=*/0,
   11455 				       TREE_VEC_LENGTH (args),
   11456 				       tsk_none);
   11457       return instantiate_template (tmpl, new_args, tf_error);
   11458     }
   11459 
   11460   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
   11461   if (new_friend == error_mark_node)
   11462     return error_mark_node;
   11463 
   11464   /* The NEW_FRIEND will look like an instantiation, to the
   11465      compiler, but is not an instantiation from the point of view of
   11466      the language.  For example, we might have had:
   11467 
   11468      template <class T> struct S {
   11469        template <class U> friend void f(T, U);
   11470      };
   11471 
   11472      Then, in S<int>, template <class U> void f(int, U) is not an
   11473      instantiation of anything.  */
   11474 
   11475   DECL_USE_TEMPLATE (new_friend) = 0;
   11476   if (TREE_CODE (new_friend) == TEMPLATE_DECL)
   11477     {
   11478       DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (new_friend) = false;
   11479       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
   11480       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
   11481 	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
   11482 
   11483       /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
   11484 	 match in decls_match.  */
   11485       tree parms = DECL_TEMPLATE_PARMS (new_friend);
   11486       tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
   11487       treqs = maybe_substitute_reqs_for (treqs, new_friend);
   11488       if (treqs != TEMPLATE_PARMS_CONSTRAINTS (parms))
   11489 	{
   11490 	  TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
   11491 	  /* As well as each TEMPLATE_PARM_CONSTRAINTS.  */
   11492 	  tsubst_each_template_parm_constraints (parms, args,
   11493 						 tf_warning_or_error);
   11494 	}
   11495     }
   11496 
   11497   /* The mangled name for the NEW_FRIEND is incorrect.  The function
   11498      is not a template instantiation and should not be mangled like
   11499      one.  Therefore, we forget the mangling here; we'll recompute it
   11500      later if we need it.  */
   11501   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
   11502     {
   11503       SET_DECL_RTL (new_friend, NULL);
   11504       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
   11505     }
   11506 
   11507   if (DECL_NAMESPACE_SCOPE_P (new_friend))
   11508     {
   11509       tree old_decl;
   11510       tree ns;
   11511 
   11512       /* We must save some information from NEW_FRIEND before calling
   11513 	 duplicate decls since that function will free NEW_FRIEND if
   11514 	 possible.  */
   11515       tree new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
   11516       tree new_friend_result_template_info = NULL_TREE;
   11517       bool new_friend_is_defn =
   11518 	(new_friend_template_info
   11519 	 && (DECL_INITIAL (DECL_TEMPLATE_RESULT
   11520 			   (template_for_substitution (new_friend)))
   11521 	     != NULL_TREE));
   11522       tree not_tmpl = new_friend;
   11523 
   11524       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
   11525 	{
   11526 	  /* This declaration is a `primary' template.  */
   11527 	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
   11528 
   11529 	  not_tmpl = DECL_TEMPLATE_RESULT (new_friend);
   11530 	  new_friend_result_template_info = DECL_TEMPLATE_INFO (not_tmpl);
   11531 	}
   11532 
   11533       /* We need to propagate module attachment for the new friend from the
   11534 	 owner of this template.  */
   11535       propagate_defining_module (new_friend, decl);
   11536 
   11537       /* Inside pushdecl_namespace_level, we will push into the
   11538 	 current namespace. However, the friend function should go
   11539 	 into the namespace of the template.  */
   11540       ns = decl_namespace_context (new_friend);
   11541       push_nested_namespace (ns);
   11542       old_decl = pushdecl_namespace_level (new_friend, /*hiding=*/true);
   11543       pop_nested_namespace (ns);
   11544 
   11545       if (old_decl == error_mark_node)
   11546 	return error_mark_node;
   11547 
   11548       if (old_decl != new_friend)
   11549 	{
   11550 	  /* This new friend declaration matched an existing
   11551 	     declaration.  For example, given:
   11552 
   11553 	       template <class T> void f(T);
   11554 	       template <class U> class C {
   11555 		 template <class T> friend void f(T) {}
   11556 	       };
   11557 
   11558 	     the friend declaration actually provides the definition
   11559 	     of `f', once C has been instantiated for some type.  So,
   11560 	     old_decl will be the out-of-class template declaration,
   11561 	     while new_friend is the in-class definition.
   11562 
   11563 	     But, if `f' was called before this point, the
   11564 	     instantiation of `f' will have DECL_TI_ARGS corresponding
   11565 	     to `T' but not to `U', references to which might appear
   11566 	     in the definition of `f'.  Previously, the most general
   11567 	     template for an instantiation of `f' was the out-of-class
   11568 	     version; now it is the in-class version.  Therefore, we
   11569 	     run through all specialization of `f', adding to their
   11570 	     DECL_TI_ARGS appropriately.  In particular, they need a
   11571 	     new set of outer arguments, corresponding to the
   11572 	     arguments for this class instantiation.
   11573 
   11574 	     The same situation can arise with something like this:
   11575 
   11576 	       friend void f(int);
   11577 	       template <class T> class C {
   11578 		 friend void f(T) {}
   11579 	       };
   11580 
   11581 	     when `C<int>' is instantiated.  Now, `f(int)' is defined
   11582 	     in the class.  */
   11583 
   11584 	  if (!new_friend_is_defn)
   11585 	    /* On the other hand, if the in-class declaration does
   11586 	       *not* provide a definition, then we don't want to alter
   11587 	       existing definitions.  We can just leave everything
   11588 	       alone.  */
   11589 	    ;
   11590 	  else
   11591 	    {
   11592 	      tree old_template = most_general_template (old_decl);
   11593 	      tree new_template = TI_TEMPLATE (new_friend_template_info);
   11594 	      tree new_args = TI_ARGS (new_friend_template_info);
   11595 
   11596 	      /* Overwrite whatever template info was there before, if
   11597 		 any, with the new template information pertaining to
   11598 		 the declaration.  */
   11599 	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
   11600 
   11601 	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
   11602 		{
   11603 		  /* We should have called reregister_specialization in
   11604 		     duplicate_decls.  */
   11605 		  gcc_assert (retrieve_specialization (new_template,
   11606 						       new_args, 0)
   11607 			      == old_decl);
   11608 
   11609 		  /* Instantiate it if the global has already been used.  */
   11610 		  if (DECL_ODR_USED (old_decl))
   11611 		    instantiate_decl (old_decl, /*defer_ok=*/true,
   11612 				      /*expl_inst_class_mem_p=*/false);
   11613 		}
   11614 	      else
   11615 		{
   11616 		  tree t;
   11617 
   11618 		  /* Indicate that the old function template is a partial
   11619 		     instantiation.  */
   11620 		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
   11621 		    = new_friend_result_template_info;
   11622 
   11623 		  gcc_assert (new_template
   11624 			      == most_general_template (new_template));
   11625 		  gcc_assert (new_template != old_decl);
   11626 
   11627 		  /* Reassign any specializations already in the hash table
   11628 		     to the new more general template, and add the
   11629 		     additional template args.  */
   11630 		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_template);
   11631 		       t != NULL_TREE;
   11632 		       t = TREE_CHAIN (t))
   11633 		    {
   11634 		      tree spec = TREE_VALUE (t);
   11635 		      spec_entry elt;
   11636 
   11637 		      elt.tmpl = old_decl;
   11638 		      elt.args = DECL_TI_ARGS (spec);
   11639 		      elt.spec = NULL_TREE;
   11640 
   11641 		      if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (DECL_TI_ARGS (spec))
   11642 			  && !is_specialization_of_friend (spec, new_template))
   11643 			continue;
   11644 
   11645 		      decl_specializations->remove_elt (&elt);
   11646 
   11647 		      tree& spec_args = DECL_TI_ARGS (spec);
   11648 		      spec_args = add_outermost_template_args
   11649 			(new_args, INNERMOST_TEMPLATE_ARGS (spec_args));
   11650 
   11651 		      register_specialization
   11652 			(spec, new_template, spec_args, true, 0);
   11653 
   11654 		    }
   11655 		  DECL_TEMPLATE_INSTANTIATIONS (old_template) = NULL_TREE;
   11656 		}
   11657 	    }
   11658 
   11659 	  /* The information from NEW_FRIEND has been merged into OLD_DECL
   11660 	     by duplicate_decls.  */
   11661 	  new_friend = old_decl;
   11662 	}
   11663 
   11664       /* We've just introduced a namespace-scope function in the purview
   11665 	 without necessarily having opened the enclosing namespace, so
   11666 	 make sure the namespace is in the purview now too.  */
   11667       if (modules_p ()
   11668 	  && DECL_MODULE_PURVIEW_P (STRIP_TEMPLATE (new_friend))
   11669 	  && TREE_CODE (DECL_CONTEXT (new_friend)) == NAMESPACE_DECL)
   11670 	DECL_MODULE_PURVIEW_P (DECL_CONTEXT (new_friend)) = true;
   11671     }
   11672   else
   11673     {
   11674       tree context = DECL_CONTEXT (new_friend);
   11675       bool dependent_p;
   11676 
   11677       /* In the code
   11678 	   template <class T> class C {
   11679 	     template <class U> friend void C1<U>::f (); // case 1
   11680 	     friend void C2<T>::f ();			 // case 2
   11681 	   };
   11682 	 we only need to make sure CONTEXT is a complete type for
   11683 	 case 2.  To distinguish between the two cases, we note that
   11684 	 CONTEXT of case 1 remains dependent type after tsubst while
   11685 	 this isn't true for case 2.  */
   11686       ++processing_template_decl;
   11687       dependent_p = dependent_type_p (context);
   11688       --processing_template_decl;
   11689 
   11690       if (!dependent_p
   11691 	  && !complete_type_or_else (context, NULL_TREE))
   11692 	return error_mark_node;
   11693 
   11694       if (COMPLETE_TYPE_P (context))
   11695 	{
   11696 	  tree fn = new_friend;
   11697 	  /* do_friend adds the TEMPLATE_DECL for any member friend
   11698 	     template even if it isn't a member template, i.e.
   11699 	       template <class T> friend A<T>::f();
   11700 	     Look through it in that case.  */
   11701 	  if (TREE_CODE (fn) == TEMPLATE_DECL
   11702 	      && !PRIMARY_TEMPLATE_P (fn))
   11703 	    fn = DECL_TEMPLATE_RESULT (fn);
   11704 	  /* Check to see that the declaration is really present, and,
   11705 	     possibly obtain an improved declaration.  */
   11706 	  fn = check_classfn (context, fn, NULL_TREE);
   11707 
   11708 	  if (fn)
   11709 	    new_friend = fn;
   11710 	}
   11711     }
   11712 
   11713   return new_friend;
   11714 }
   11715 
   11716 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
   11717    template arguments, as for tsubst.
   11718 
   11719    Returns an appropriate tsubst'd friend type or error_mark_node on
   11720    failure.  */
   11721 
   11722 static tree
   11723 tsubst_friend_class (tree friend_tmpl, tree args)
   11724 {
   11725   tree tmpl;
   11726 
   11727   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
   11728     {
   11729       tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
   11730       return TREE_TYPE (tmpl);
   11731     }
   11732 
   11733   tree context = CP_DECL_CONTEXT (friend_tmpl);
   11734   if (TREE_CODE (context) == NAMESPACE_DECL)
   11735     push_nested_namespace (context);
   11736   else
   11737     {
   11738       context = tsubst (context, args, tf_error, NULL_TREE);
   11739       push_nested_class (context);
   11740     }
   11741 
   11742   tmpl = lookup_name (DECL_NAME (friend_tmpl), LOOK_where::CLASS_NAMESPACE,
   11743 		      LOOK_want::NORMAL | LOOK_want::HIDDEN_FRIEND);
   11744 
   11745   if (!tmpl)
   11746     /* If we didn't find by name lookup, the type may still exist but as a
   11747        'hidden' import; we should check for this too to avoid accidentally
   11748        instantiating a duplicate.  */
   11749     tmpl = lookup_imported_hidden_friend (friend_tmpl);
   11750 
   11751   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
   11752     {
   11753       /* The friend template has already been declared.  Just
   11754 	 check to see that the declarations match, and install any new
   11755 	 default parameters.  We must tsubst the default parameters,
   11756 	 of course.  We only need the innermost template parameters
   11757 	 because that is all that redeclare_class_template will look
   11758 	 at.  */
   11759 
   11760       if (modules_p ())
   11761 	/* Check that the existing declaration's module attachment is
   11762 	   compatible with the attachment of the friend template.  */
   11763 	module_may_redeclare (tmpl, friend_tmpl);
   11764 
   11765       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
   11766 	  > TMPL_ARGS_DEPTH (args))
   11767 	{
   11768 	  tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
   11769 					      args, tf_warning_or_error);
   11770 	  tsubst_each_template_parm_constraints (parms, args,
   11771 						 tf_warning_or_error);
   11772           location_t saved_input_location = input_location;
   11773           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
   11774 	  tree cons = get_constraints (friend_tmpl);
   11775 	  ++processing_template_decl;
   11776 	  cons = tsubst_constraint_info (cons, args, tf_warning_or_error,
   11777 					 DECL_FRIEND_CONTEXT (friend_tmpl));
   11778 	  --processing_template_decl;
   11779           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
   11780           input_location = saved_input_location;
   11781 	}
   11782     }
   11783   else
   11784     {
   11785       /* The friend template has not already been declared.  In this
   11786 	 case, the instantiation of the template class will cause the
   11787 	 injection of this template into the namespace scope.  */
   11788       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
   11789 
   11790       if (tmpl != error_mark_node)
   11791 	{
   11792 	  /* The new TMPL is not an instantiation of anything, so we
   11793 	     forget its origins.  It is also not a specialization of
   11794 	     anything.  We don't reset CLASSTYPE_TI_TEMPLATE
   11795 	     for the new type because that is supposed to be the
   11796 	     corresponding template decl, i.e., TMPL.  */
   11797 	  if (modules_p ())
   11798 	    {
   11799 	      spec_entry elt;
   11800 	      elt.tmpl = friend_tmpl;
   11801 	      elt.args = CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl));
   11802 	      elt.spec = TREE_TYPE (tmpl);
   11803 	      type_specializations->remove_elt (&elt);
   11804 	    }
   11805 
   11806 	  DECL_USE_TEMPLATE (tmpl) = 0;
   11807 	  DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
   11808 	  CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
   11809 	  CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
   11810 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
   11811 
   11812 	  /* Substitute into and set the constraints on the new declaration.  */
   11813 	  if (tree ci = get_constraints (friend_tmpl))
   11814 	    {
   11815 	      ++processing_template_decl;
   11816 	      ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
   11817 					   DECL_FRIEND_CONTEXT (friend_tmpl));
   11818 	      --processing_template_decl;
   11819 	      set_constraints (tmpl, ci);
   11820 	      tsubst_each_template_parm_constraints (DECL_TEMPLATE_PARMS (tmpl),
   11821 						     args, tf_warning_or_error);
   11822 	    }
   11823 
   11824 	  /* We need to propagate the attachment of the original template to the
   11825 	     newly instantiated template type.  */
   11826 	  propagate_defining_module (tmpl, friend_tmpl);
   11827 
   11828 	  /* Inject this template into the enclosing namspace scope.  */
   11829 	  tmpl = pushdecl_namespace_level (tmpl, /*hiding=*/true);
   11830 	}
   11831     }
   11832 
   11833   if (TREE_CODE (context) == NAMESPACE_DECL)
   11834     pop_nested_namespace (context);
   11835   else
   11836     pop_nested_class ();
   11837 
   11838   return TREE_TYPE (tmpl);
   11839 }
   11840 
   11841 /* Returns zero if TYPE cannot be completed later due to circularity.
   11842    Otherwise returns one.  */
   11843 
   11844 static int
   11845 can_complete_type_without_circularity (tree type)
   11846 {
   11847   if (type == NULL_TREE || type == error_mark_node)
   11848     return 0;
   11849   else if (COMPLETE_TYPE_P (type))
   11850     return 1;
   11851   else if (TREE_CODE (type) == ARRAY_TYPE)
   11852     return can_complete_type_without_circularity (TREE_TYPE (type));
   11853   else if (CLASS_TYPE_P (type)
   11854 	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
   11855     return 0;
   11856   else
   11857     return 1;
   11858 }
   11859 
   11860 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
   11861 				tsubst_flags_t, tree);
   11862 
   11863 /* Instantiate the contract statement.  */
   11864 
   11865 static tree
   11866 tsubst_contract (tree decl, tree t, tree args, tsubst_flags_t complain,
   11867 		 tree in_decl)
   11868 {
   11869   tree type = decl ? TREE_TYPE (TREE_TYPE (decl)) : NULL_TREE;
   11870   bool auto_p  = type_uses_auto (type);
   11871 
   11872   tree r = copy_node (t);
   11873 
   11874   /* Rebuild the result variable.  */
   11875   if (type && POSTCONDITION_P (t) && POSTCONDITION_IDENTIFIER (t))
   11876     {
   11877       tree oldvar = POSTCONDITION_IDENTIFIER (t);
   11878 
   11879       tree newvar = copy_node (oldvar);
   11880       TREE_TYPE (newvar) = type;
   11881       DECL_CONTEXT (newvar) = decl;
   11882       POSTCONDITION_IDENTIFIER (r) = newvar;
   11883 
   11884       /* Make sure the postcondition is valid.  */
   11885       location_t loc = DECL_SOURCE_LOCATION (oldvar);
   11886       if (!auto_p)
   11887 	if (!check_postcondition_result (decl, type, loc))
   11888 	  return invalidate_contract (r);
   11889 
   11890       /* Make the variable available for lookup.  */
   11891       register_local_specialization (newvar, oldvar);
   11892     }
   11893 
   11894   /* Instantiate the condition.  If the return type is undeduced, process
   11895      the expression as if inside a template to avoid spurious type errors.  */
   11896   if (auto_p)
   11897     ++processing_template_decl;
   11898   ++processing_contract_condition;
   11899   CONTRACT_CONDITION (r)
   11900       = tsubst_expr (CONTRACT_CONDITION (t), args, complain, in_decl);
   11901   --processing_contract_condition;
   11902   if (auto_p)
   11903     --processing_template_decl;
   11904 
   11905   /* And the comment.  */
   11906   CONTRACT_COMMENT (r)
   11907       = tsubst_expr (CONTRACT_COMMENT (r), args, complain, in_decl);
   11908 
   11909   return r;
   11910 }
   11911 
   11912 /* Update T by instantiating its contract attribute.  */
   11913 
   11914 static void
   11915 tsubst_contract_attribute (tree decl, tree t, tree args,
   11916 			   tsubst_flags_t complain, tree in_decl)
   11917 {
   11918   /* For non-specializations, adjust the current declaration to the most general
   11919      version of in_decl. Because we defer the instantiation of contracts as long
   11920      as possible, they are still written in terms of the parameters (and return
   11921      type) of the most general template.  */
   11922   tree tmpl = DECL_TI_TEMPLATE (in_decl);
   11923   if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
   11924     in_decl = DECL_TEMPLATE_RESULT (most_general_template (in_decl));
   11925   local_specialization_stack specs (lss_copy);
   11926   register_parameter_specializations (in_decl, decl);
   11927 
   11928   /* Get the contract to be instantiated.  */
   11929   tree contract = CONTRACT_STATEMENT (t);
   11930 
   11931   /* Use the complete set of template arguments for instantiation. The
   11932      contract may not have been instantiated and still refer to outer levels
   11933      of template parameters.  */
   11934   args = DECL_TI_ARGS (decl);
   11935 
   11936   /* For member functions, make this available for semantic analysis.  */
   11937   tree save_ccp = current_class_ptr;
   11938   tree save_ccr = current_class_ref;
   11939   if (DECL_IOBJ_MEMBER_FUNCTION_P (decl))
   11940     {
   11941       tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
   11942       tree this_type = TREE_TYPE (TREE_VALUE (arg_types));
   11943       inject_this_parameter (this_type, cp_type_quals (this_type));
   11944     }
   11945 
   11946   contract = tsubst_contract (decl, contract, args, complain, in_decl);
   11947 
   11948   current_class_ptr = save_ccp;
   11949   current_class_ref = save_ccr;
   11950 
   11951   /* Rebuild the attribute.  */
   11952   TREE_VALUE (t) = build_tree_list (NULL_TREE, contract);
   11953 }
   11954 
   11955 /* Rebuild the attribute list for DECL, substituting into contracts
   11956    as needed.  */
   11957 
   11958 void
   11959 tsubst_contract_attributes (tree decl, tree args, tsubst_flags_t complain, tree in_decl)
   11960 {
   11961   tree list = copy_list (DECL_ATTRIBUTES (decl));
   11962   for (tree attr = list; attr; attr = CONTRACT_CHAIN (attr))
   11963     {
   11964       if (cxx_contract_attribute_p (attr))
   11965 	tsubst_contract_attribute (decl, attr, args, complain, in_decl);
   11966     }
   11967   DECL_ATTRIBUTES (decl) = list;
   11968 }
   11969 
   11970 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
   11971    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
   11972 
   11973 static tree
   11974 tsubst_attribute (tree t, tree *decl_p, tree args,
   11975 		  tsubst_flags_t complain, tree in_decl)
   11976 {
   11977   gcc_assert (ATTR_IS_DEPENDENT (t));
   11978 
   11979   /* Note that contract attributes are never substituted from this function.
   11980      Their instantiation is triggered by regenerate_from_template_decl when
   11981      we instantiate the body of the function.  */
   11982 
   11983   tree val = TREE_VALUE (t);
   11984   if (val == NULL_TREE)
   11985     /* Nothing to do.  */;
   11986   else if ((flag_openmp || flag_openmp_simd)
   11987 	   && is_attribute_p ("omp declare simd",
   11988 			      get_attribute_name (t)))
   11989     {
   11990       tree clauses = TREE_VALUE (val);
   11991       clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
   11992 				    complain, in_decl);
   11993       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
   11994       clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
   11995       tree parms = DECL_ARGUMENTS (*decl_p);
   11996       clauses
   11997 	= c_omp_declare_simd_clauses_to_numbers (parms, clauses);
   11998       if (clauses)
   11999 	val = build_tree_list (NULL_TREE, clauses);
   12000       else
   12001 	val = NULL_TREE;
   12002     }
   12003   else if (flag_openmp
   12004 	   && is_attribute_p ("omp declare variant base",
   12005 			      get_attribute_name (t)))
   12006     {
   12007       ++cp_unevaluated_operand;
   12008       tree varid = tsubst_expr (TREE_PURPOSE (val), args, complain, in_decl);
   12009       --cp_unevaluated_operand;
   12010       tree chain = TREE_CHAIN (val);
   12011       location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
   12012       tree ctx = copy_list (TREE_VALUE (val));
   12013       for (tree tss = ctx; tss; tss = TREE_CHAIN (tss))
   12014 	{
   12015 	  enum omp_tss_code set = OMP_TSS_CODE (tss);
   12016 	  tree selectors = NULL_TREE;
   12017 	  for (tree ts = OMP_TSS_TRAIT_SELECTORS (tss); ts;
   12018 	       ts = TREE_CHAIN (ts))
   12019 	    {
   12020 	      tree properties = NULL_TREE;
   12021 	      tree scoreval = NULL_TREE;
   12022 	      /* FIXME: The body of this loop should really be dispatching
   12023 		 according to omp_ts_map[OMP_TS_CODE (TS)].tp_type instead
   12024 		 of having hard-wired knowledge of specific selectors.  */
   12025 	      if (OMP_TS_CODE (ts) == OMP_TRAIT_CONSTRUCT_SIMD
   12026 		  && set == OMP_TRAIT_SET_CONSTRUCT)
   12027 		{
   12028 		  tree clauses = OMP_TS_PROPERTIES (ts);
   12029 		  clauses = tsubst_omp_clauses (clauses,
   12030 						C_ORT_OMP_DECLARE_SIMD, args,
   12031 						complain, in_decl);
   12032 		  c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
   12033 		  clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
   12034 		  properties = clauses;
   12035 		}
   12036 	      else
   12037 		{
   12038 		  tree v = OMP_TS_SCORE (ts);
   12039 		  if (v)
   12040 		    {
   12041 		      v = tsubst_expr (v, args, complain, in_decl);
   12042 		      v = fold_non_dependent_expr (v);
   12043 		      if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
   12044 			  || TREE_CODE (v) != INTEGER_CST)
   12045 			{
   12046 			  location_t loc
   12047 			    = cp_expr_loc_or_loc (OMP_TS_SCORE (ts),
   12048 						  match_loc);
   12049 			  error_at (loc, "score argument must be "
   12050 				    "constant integer expression");
   12051 			  return NULL_TREE;
   12052 			}
   12053 		      else if (tree_int_cst_sgn (v) < 0)
   12054 			{
   12055 			  location_t loc
   12056 			    = cp_expr_loc_or_loc (OMP_TS_SCORE (ts),
   12057 						  match_loc);
   12058 			  error_at (loc, "score argument must be "
   12059 				    "non-negative");
   12060 			  return NULL_TREE;
   12061 			}
   12062 		      scoreval = v;
   12063 		    }
   12064 		  properties = copy_list (OMP_TS_PROPERTIES (ts));
   12065 		  for (tree p = properties; p; p = TREE_CHAIN (p))
   12066 		    if (OMP_TP_NAME (p) == OMP_TP_NAMELIST_NODE)
   12067 		      continue;
   12068 		    else if (OMP_TP_VALUE (p))
   12069 		      {
   12070 			bool allow_string
   12071 			  = (OMP_TS_CODE (ts) != OMP_TRAIT_USER_CONDITION
   12072 			     || set != OMP_TRAIT_SET_USER);
   12073 			tree v = OMP_TP_VALUE (p);
   12074 			if (TREE_CODE (v) == STRING_CST && allow_string)
   12075 			  continue;
   12076 			v = tsubst_expr (v, args, complain, in_decl);
   12077 			v = fold_non_dependent_expr (v);
   12078 			if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
   12079 			    || !tree_fits_shwi_p (v))
   12080 			  {
   12081 			    location_t loc
   12082 			      = cp_expr_loc_or_loc (OMP_TP_VALUE (p),
   12083 						    match_loc);
   12084 			    if (allow_string)
   12085 			      error_at (loc, "property must be constant "
   12086 					     "integer expression or string "
   12087 					     "literal");
   12088 			    else
   12089 			      error_at (loc, "property must be constant "
   12090 					     "integer expression");
   12091 			    return NULL_TREE;
   12092 			  }
   12093 			OMP_TP_VALUE (p) = v;
   12094 		      }
   12095 		}
   12096 	      selectors = make_trait_selector (OMP_TS_CODE (ts), scoreval,
   12097 					       properties, selectors);
   12098 	    }
   12099 	  OMP_TSS_TRAIT_SELECTORS (tss) = nreverse (selectors);
   12100 	}
   12101       val = tree_cons (varid, ctx, chain);
   12102     }
   12103   /* If the first attribute argument is an identifier, don't
   12104      pass it through tsubst.  Attributes like mode, format,
   12105      cleanup and several target specific attributes expect it
   12106      unmodified.  */
   12107   else if (attribute_takes_identifier_p (get_attribute_name (t)))
   12108     {
   12109       tree chain
   12110 	= tsubst_expr (TREE_CHAIN (val), args, complain, in_decl);
   12111       if (chain != TREE_CHAIN (val))
   12112 	val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
   12113     }
   12114   else if (PACK_EXPANSION_P (val))
   12115     {
   12116       /* An attribute pack expansion.  */
   12117       tree purp = TREE_PURPOSE (t);
   12118       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
   12119       if (pack == error_mark_node)
   12120 	return error_mark_node;
   12121       int len = TREE_VEC_LENGTH (pack);
   12122       tree list = NULL_TREE;
   12123       tree *q = &list;
   12124       for (int i = 0; i < len; ++i)
   12125 	{
   12126 	  tree elt = TREE_VEC_ELT (pack, i);
   12127 	  *q = build_tree_list (purp, elt);
   12128 	  q = &TREE_CHAIN (*q);
   12129 	}
   12130       return list;
   12131     }
   12132   else
   12133     val = tsubst_expr (val, args, complain, in_decl);
   12134 
   12135   if (val == error_mark_node)
   12136     return error_mark_node;
   12137   if (val != TREE_VALUE (t))
   12138     return build_tree_list (TREE_PURPOSE (t), val);
   12139   return t;
   12140 }
   12141 
   12142 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
   12143    unchanged or a new TREE_LIST chain.  */
   12144 
   12145 static tree
   12146 tsubst_attributes (tree attributes, tree args,
   12147 		   tsubst_flags_t complain, tree in_decl)
   12148 {
   12149   tree last_dep = NULL_TREE;
   12150 
   12151   for (tree t = attributes; t; t = TREE_CHAIN (t))
   12152     if (ATTR_IS_DEPENDENT (t))
   12153       {
   12154 	last_dep = t;
   12155 	attributes = copy_list (attributes);
   12156 	break;
   12157       }
   12158 
   12159   if (last_dep)
   12160     for (tree *p = &attributes; *p; )
   12161       {
   12162 	tree t = *p;
   12163 	if (ATTR_IS_DEPENDENT (t))
   12164 	  {
   12165 	    tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
   12166 	    if (subst != t)
   12167 	      {
   12168 		*p = subst;
   12169 		while (*p)
   12170 		  p = &TREE_CHAIN (*p);
   12171 		*p = TREE_CHAIN (t);
   12172 		continue;
   12173 	      }
   12174 	  }
   12175 	p = &TREE_CHAIN (*p);
   12176       }
   12177 
   12178   return attributes;
   12179 }
   12180 
   12181 /* Apply any attributes which had to be deferred until instantiation
   12182    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
   12183    ARGS, COMPLAIN, IN_DECL are as tsubst.  Returns true normally,
   12184    false on error.  */
   12185 
   12186 static bool
   12187 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
   12188 				tree args, tsubst_flags_t complain, tree in_decl)
   12189 {
   12190   tree t;
   12191   tree *p;
   12192 
   12193   if (attributes == NULL_TREE)
   12194     return true;
   12195 
   12196   if (DECL_P (*decl_p))
   12197     {
   12198       if (TREE_TYPE (*decl_p) == error_mark_node)
   12199 	return false;
   12200       p = &DECL_ATTRIBUTES (*decl_p);
   12201       /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
   12202          to our attributes parameter.  */
   12203       gcc_assert (*p == attributes);
   12204     }
   12205   else
   12206     {
   12207       p = &TYPE_ATTRIBUTES (*decl_p);
   12208       /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
   12209 	 lookup_template_class_1, and should be preserved.  */
   12210       gcc_assert (*p != attributes);
   12211       while (*p)
   12212 	p = &TREE_CHAIN (*p);
   12213     }
   12214 
   12215   /* save_template_attributes puts the dependent attributes at the beginning of
   12216      the list; find the non-dependent ones.  */
   12217   for (t = attributes; t; t = TREE_CHAIN (t))
   12218     if (!ATTR_IS_DEPENDENT (t))
   12219       break;
   12220   tree nondep = t;
   12221 
   12222   /* Apply any non-dependent attributes.  */
   12223   *p = nondep;
   12224 
   12225   if (nondep == attributes)
   12226     return true;
   12227 
   12228   /* And then any dependent ones.  */
   12229   tree late_attrs = NULL_TREE;
   12230   tree *q = &late_attrs;
   12231   for (t = attributes; t != nondep; t = TREE_CHAIN (t))
   12232     {
   12233       *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
   12234       if (*q == error_mark_node)
   12235 	return false;
   12236       if (*q == t)
   12237 	{
   12238 	  *q = copy_node (t);
   12239 	  TREE_CHAIN (*q) = NULL_TREE;
   12240 	}
   12241       while (*q)
   12242 	q = &TREE_CHAIN (*q);
   12243     }
   12244 
   12245   /* cplus_decl_attributes can add some attributes implicitly.  For templates,
   12246      those attributes should have been added already when those templates were
   12247      parsed, and shouldn't be added based on from which context they are
   12248      first time instantiated.  */
   12249   auto o1 = make_temp_override (current_optimize_pragma, NULL_TREE);
   12250   auto o2 = make_temp_override (optimization_current_node,
   12251 				optimization_default_node);
   12252   auto o3 = make_temp_override (current_target_pragma, NULL_TREE);
   12253   auto o4 = make_temp_override (scope_chain->omp_declare_target_attribute,
   12254 				NULL);
   12255   auto o5 = make_temp_override (scope_chain->omp_begin_assumes, NULL);
   12256   auto o6 = make_temp_override (target_option_current_node,
   12257 				target_option_default_node);
   12258 
   12259   cplus_decl_attributes (decl_p, late_attrs, attr_flags);
   12260 
   12261   return true;
   12262 }
   12263 
   12264 /* The template TMPL is being instantiated with the template arguments TARGS.
   12265    Perform the access checks that we deferred when parsing the template.  */
   12266 
   12267 static void
   12268 perform_instantiation_time_access_checks (tree tmpl, tree targs)
   12269 {
   12270   unsigned i;
   12271   deferred_access_check *chk;
   12272 
   12273   if (!CLASS_TYPE_P (tmpl) && TREE_CODE (tmpl) != FUNCTION_DECL)
   12274     return;
   12275 
   12276   if (vec<deferred_access_check, va_gc> *access_checks
   12277       = TI_DEFERRED_ACCESS_CHECKS (get_template_info (tmpl)))
   12278     FOR_EACH_VEC_ELT (*access_checks, i, chk)
   12279       {
   12280 	tree decl = chk->decl;
   12281 	tree diag_decl = chk->diag_decl;
   12282 	tree type_scope = TREE_TYPE (chk->binfo);
   12283 
   12284 	if (uses_template_parms (type_scope))
   12285 	  type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
   12286 
   12287 	/* Make access check error messages point to the location
   12288 	   of the use of the typedef.  */
   12289 	iloc_sentinel ils (chk->loc);
   12290 	perform_or_defer_access_check (TYPE_BINFO (type_scope),
   12291 				       decl, diag_decl, tf_warning_or_error);
   12292       }
   12293 }
   12294 
   12295 tree
   12296 instantiate_class_template (tree type)
   12297 {
   12298   auto_timevar tv (TV_TEMPLATE_INST);
   12299 
   12300   tree templ, args, pattern, t, member;
   12301   tree typedecl;
   12302   tree pbinfo;
   12303   tree base_list;
   12304   unsigned int saved_maximum_field_alignment;
   12305   tree fn_context;
   12306 
   12307   if (type == error_mark_node)
   12308     return error_mark_node;
   12309 
   12310   if (COMPLETE_OR_OPEN_TYPE_P (type)
   12311       || uses_template_parms (type))
   12312     return type;
   12313 
   12314   /* Figure out which template is being instantiated.  */
   12315   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
   12316   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
   12317 
   12318   /* Mark the type as in the process of being defined.  */
   12319   TYPE_BEING_DEFINED (type) = 1;
   12320 
   12321   /* We may be in the middle of deferred access check.  Disable
   12322      it now.  */
   12323   deferring_access_check_sentinel acs (dk_no_deferred);
   12324 
   12325   /* Determine what specialization of the original template to
   12326      instantiate.  */
   12327   t = most_specialized_partial_spec (type, tf_warning_or_error);
   12328   if (t == error_mark_node)
   12329     return error_mark_node;
   12330   else if (t)
   12331     {
   12332       /* This TYPE is actually an instantiation of a partial
   12333 	 specialization.  We replace the innermost set of ARGS with
   12334 	 the arguments appropriate for substitution.  For example,
   12335 	 given:
   12336 
   12337 	   template <class T> struct S {};
   12338 	   template <class T> struct S<T*> {};
   12339 
   12340 	 and supposing that we are instantiating S<int*>, ARGS will
   12341 	 presently be {int*} -- but we need {int}.  */
   12342       pattern = TREE_TYPE (TI_TEMPLATE (t));
   12343       args = TI_ARGS (t);
   12344     }
   12345   else
   12346     {
   12347       pattern = TREE_TYPE (templ);
   12348       args = CLASSTYPE_TI_ARGS (type);
   12349     }
   12350 
   12351   /* If the template we're instantiating is incomplete, then clearly
   12352      there's nothing we can do.  */
   12353   if (!COMPLETE_TYPE_P (pattern))
   12354     {
   12355       /* We can try again later.  */
   12356       TYPE_BEING_DEFINED (type) = 0;
   12357       return type;
   12358     }
   12359 
   12360   /* If we've recursively instantiated too many templates, stop.  */
   12361   if (! push_tinst_level (type))
   12362     return type;
   12363 
   12364   int saved_unevaluated_operand = cp_unevaluated_operand;
   12365   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
   12366 
   12367   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
   12368   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
   12369   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
   12370     fn_context = error_mark_node;
   12371   if (!fn_context)
   12372     push_to_top_level ();
   12373   else
   12374     {
   12375       cp_unevaluated_operand = 0;
   12376       c_inhibit_evaluation_warnings = 0;
   12377     }
   12378 
   12379   mark_template_arguments_used (templ, CLASSTYPE_TI_ARGS (type));
   12380 
   12381   /* Use #pragma pack from the template context.  */
   12382   saved_maximum_field_alignment = maximum_field_alignment;
   12383   maximum_field_alignment = TYPE_PRECISION (pattern);
   12384 
   12385   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
   12386 
   12387   /* Set the input location to the most specialized template definition.
   12388      This is needed if tsubsting causes an error.  */
   12389   typedecl = TYPE_MAIN_DECL (pattern);
   12390   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
   12391     DECL_SOURCE_LOCATION (typedecl);
   12392 
   12393   set_instantiating_module (TYPE_NAME (type));
   12394 
   12395   TYPE_PACKED (type) = TYPE_PACKED (pattern);
   12396   SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
   12397   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
   12398   CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
   12399   if (ANON_AGGR_TYPE_P (pattern))
   12400     SET_ANON_AGGR_TYPE_P (type);
   12401   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
   12402     {
   12403       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
   12404       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
   12405       /* Adjust visibility for template arguments.  */
   12406       determine_visibility (TYPE_MAIN_DECL (type));
   12407     }
   12408   if (CLASS_TYPE_P (type))
   12409     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
   12410 
   12411   pbinfo = TYPE_BINFO (pattern);
   12412 
   12413   /* We should never instantiate a nested class before its enclosing
   12414      class; we need to look up the nested class by name before we can
   12415      instantiate it, and that lookup should instantiate the enclosing
   12416      class.  */
   12417   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
   12418 	      || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
   12419 
   12420   base_list = NULL_TREE;
   12421   /* Defer access checking while we substitute into the types named in
   12422      the base-clause.  */
   12423   push_deferring_access_checks (dk_deferred);
   12424   if (BINFO_N_BASE_BINFOS (pbinfo))
   12425     {
   12426       tree pbase_binfo;
   12427       int i;
   12428 
   12429       /* Substitute into each of the bases to determine the actual
   12430 	 basetypes.  */
   12431       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
   12432 	{
   12433 	  tree base;
   12434 	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
   12435           tree expanded_bases = NULL_TREE;
   12436           int idx, len = 1;
   12437 
   12438           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
   12439             {
   12440               expanded_bases =
   12441 		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
   12442 				       args, tf_error, NULL_TREE);
   12443               if (expanded_bases == error_mark_node)
   12444                 continue;
   12445 
   12446               len = TREE_VEC_LENGTH (expanded_bases);
   12447             }
   12448 
   12449           for (idx = 0; idx < len; idx++)
   12450             {
   12451               if (expanded_bases)
   12452                 /* Extract the already-expanded base class.  */
   12453                 base = TREE_VEC_ELT (expanded_bases, idx);
   12454               else
   12455                 /* Substitute to figure out the base class.  */
   12456                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
   12457                                NULL_TREE);
   12458 
   12459               if (base == error_mark_node)
   12460                 continue;
   12461 
   12462               base_list = tree_cons (access, base, base_list);
   12463               if (BINFO_VIRTUAL_P (pbase_binfo))
   12464                 TREE_TYPE (base_list) = integer_type_node;
   12465             }
   12466 	}
   12467 
   12468       /* The list is now in reverse order; correct that.  */
   12469       base_list = nreverse (base_list);
   12470     }
   12471   /* Now call xref_basetypes to set up all the base-class
   12472      information.  */
   12473   xref_basetypes (type, base_list);
   12474 
   12475   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
   12476 				  (int) ATTR_FLAG_TYPE_IN_PLACE,
   12477 				  args, tf_error, NULL_TREE);
   12478   fixup_attribute_variants (type);
   12479 
   12480   /* Now that our base classes are set up, enter the scope of the
   12481      class, so that name lookups into base classes, etc. will work
   12482      correctly.  This is precisely analogous to what we do in
   12483      begin_class_definition when defining an ordinary non-template
   12484      class, except we also need to push the enclosing classes.  */
   12485   push_nested_class (type);
   12486 
   12487   /* Now check accessibility of the types named in its base-clause,
   12488      relative to the scope of the class.  */
   12489   pop_to_parent_deferring_access_checks ();
   12490 
   12491   /* A vector to hold members marked with attribute used. */
   12492   auto_vec<tree> used;
   12493 
   12494   /* Now members are processed in the order of declaration.  */
   12495   for (member = CLASSTYPE_DECL_LIST (pattern);
   12496        member; member = TREE_CHAIN (member))
   12497     {
   12498       tree t = TREE_VALUE (member);
   12499 
   12500       if (TREE_PURPOSE (member))
   12501 	{
   12502 	  if (TYPE_P (t))
   12503 	    {
   12504 	      if (LAMBDA_TYPE_P (t))
   12505 		/* A closure type for a lambda in an NSDMI or default argument.
   12506 		   Ignore it; it will be regenerated when needed.  */
   12507 		continue;
   12508 
   12509 	      /* If the member is a class template, we've
   12510 		 already substituted its type.  */
   12511 	      if (CLASS_TYPE_P (t)
   12512 		  && CLASSTYPE_IS_TEMPLATE (t))
   12513 		continue;
   12514 
   12515 	      tree newtag = tsubst (t, args, tf_error, NULL_TREE);
   12516 	      if (newtag == error_mark_node)
   12517 		continue;
   12518 
   12519 	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
   12520 		{
   12521 		  tree name = TYPE_IDENTIFIER (t);
   12522 
   12523 		  /* Now, install the tag.  We don't use pushtag
   12524 		     because that does too much work -- creating an
   12525 		     implicit typedef, which we've already done.  */
   12526 		  set_identifier_type_value (name, TYPE_NAME (newtag));
   12527 		  maybe_add_class_template_decl_list (type, newtag, false);
   12528 		  TREE_PUBLIC (TYPE_NAME (newtag)) = true;
   12529 		  determine_visibility (TYPE_NAME (newtag));
   12530 		}
   12531 	    }
   12532 	  else if (DECL_DECLARES_FUNCTION_P (t))
   12533 	    {
   12534 	      tree r;
   12535 
   12536 	      if (TREE_CODE (t) == TEMPLATE_DECL)
   12537 		++processing_template_decl;
   12538 	      r = tsubst (t, args, tf_error, NULL_TREE);
   12539 	      if (TREE_CODE (t) == TEMPLATE_DECL)
   12540 		--processing_template_decl;
   12541 
   12542 	      set_current_access_from_decl (r);
   12543 	      finish_member_declaration (r);
   12544 	      /* Instantiate members marked with attribute used.  */
   12545 	      if (r != error_mark_node && DECL_PRESERVE_P (r))
   12546 		used.safe_push (r);
   12547 	      if (TREE_CODE (r) == FUNCTION_DECL
   12548 		  && DECL_OMP_DECLARE_REDUCTION_P (r))
   12549 		cp_check_omp_declare_reduction (r);
   12550 	    }
   12551 	  else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
   12552 		   && LAMBDA_TYPE_P (TREE_TYPE (t)))
   12553 	    /* A closure type for a lambda in an NSDMI or default argument.
   12554 	       Ignore it; it will be regenerated when needed.  */;
   12555 	  else
   12556 	    {
   12557 	      /* Build new TYPE_FIELDS.  */
   12558               if (TREE_CODE (t) == STATIC_ASSERT)
   12559 		tsubst_stmt (t, args, tf_warning_or_error, NULL_TREE);
   12560 	      else if (TREE_CODE (t) != CONST_DECL)
   12561 		{
   12562 		  tree r;
   12563 		  tree vec = NULL_TREE;
   12564 		  int len = 1;
   12565 
   12566 		  gcc_checking_assert (TREE_CODE (t) != CONST_DECL);
   12567 		  /* The file and line for this declaration, to
   12568 		     assist in error message reporting.  Since we
   12569 		     called push_tinst_level above, we don't need to
   12570 		     restore these.  */
   12571 		  input_location = DECL_SOURCE_LOCATION (t);
   12572 
   12573 		  if (TREE_CODE (t) == TEMPLATE_DECL)
   12574 		    ++processing_template_decl;
   12575 		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
   12576 		  if (TREE_CODE (t) == TEMPLATE_DECL)
   12577 		    --processing_template_decl;
   12578 
   12579 		  if (TREE_CODE (r) == TREE_VEC)
   12580 		    {
   12581 		      /* A capture pack became multiple fields.  */
   12582 		      vec = r;
   12583 		      len = TREE_VEC_LENGTH (vec);
   12584 		    }
   12585 
   12586 		  for (int i = 0; i < len; ++i)
   12587 		    {
   12588 		      if (vec)
   12589 			r = TREE_VEC_ELT (vec, i);
   12590 		      if (VAR_P (r))
   12591 			{
   12592 			  /* In [temp.inst]:
   12593 
   12594 			     [t]he initialization (and any associated
   12595 			     side-effects) of a static data member does
   12596 			     not occur unless the static data member is
   12597 			     itself used in a way that requires the
   12598 			     definition of the static data member to
   12599 			     exist.
   12600 
   12601 			     Therefore, we do not substitute into the
   12602 			     initialized for the static data member here.  */
   12603 			  finish_static_data_member_decl
   12604 			    (r,
   12605 			     /*init=*/NULL_TREE,
   12606 			     /*init_const_expr_p=*/false,
   12607 			     /*asmspec_tree=*/NULL_TREE,
   12608 			     /*flags=*/0);
   12609 			  /* Instantiate members marked with attribute used. */
   12610 			  if (r != error_mark_node && DECL_PRESERVE_P (r))
   12611 			    used.safe_push (r);
   12612 			}
   12613 		      else if (TREE_CODE (r) == FIELD_DECL)
   12614 			{
   12615 			  /* Determine whether R has a valid type and can be
   12616 			     completed later.  If R is invalid, then its type
   12617 			     is replaced by error_mark_node.  */
   12618 			  tree rtype = TREE_TYPE (r);
   12619 			  if (can_complete_type_without_circularity (rtype))
   12620 			    complete_type (rtype);
   12621 
   12622 			  if (!complete_or_array_type_p (rtype))
   12623 			    {
   12624 			      /* If R's type couldn't be completed and
   12625 				 it isn't a flexible array member (whose
   12626 				 type is incomplete by definition) give
   12627 				 an error.  */
   12628 			      cxx_incomplete_type_error (r, rtype);
   12629 			      TREE_TYPE (r) = error_mark_node;
   12630 			    }
   12631 			  else if (TREE_CODE (rtype) == ARRAY_TYPE
   12632 				   && TYPE_DOMAIN (rtype) == NULL_TREE
   12633 				   && (TREE_CODE (type) == UNION_TYPE
   12634 				       || TREE_CODE (type) == QUAL_UNION_TYPE))
   12635 			    {
   12636 			      error ("flexible array member %qD in union", r);
   12637 			      TREE_TYPE (r) = error_mark_node;
   12638 			    }
   12639 			  else if (!verify_type_context (input_location,
   12640 							 TCTX_FIELD, rtype))
   12641 			    TREE_TYPE (r) = error_mark_node;
   12642 			}
   12643 
   12644 		      /* If it is a TYPE_DECL for a class-scoped
   12645 			 ENUMERAL_TYPE, such a thing will already have
   12646 			 been added to the field list by tsubst_enum
   12647 			 in finish_member_declaration case above.  */
   12648 		      if (!(TREE_CODE (r) == TYPE_DECL
   12649 			    && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
   12650 			    && DECL_ARTIFICIAL (r)))
   12651 			{
   12652 			  set_current_access_from_decl (r);
   12653 			  finish_member_declaration (r);
   12654 			}
   12655 		    }
   12656 		}
   12657 	    }
   12658 	}
   12659       else
   12660 	{
   12661 	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
   12662 	      || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
   12663 	    {
   12664 	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
   12665 
   12666 	      tree friend_type = t;
   12667 	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
   12668 		{
   12669 		  /* template <class T> friend class C;  */
   12670 		  friend_type = tsubst_friend_class (friend_type, args);
   12671 		}
   12672 	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
   12673 		{
   12674 		  /* template <class T> friend class C::D;  */
   12675 		  friend_type = tsubst (friend_type, args,
   12676 					tf_warning_or_error, NULL_TREE);
   12677 		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
   12678 		    friend_type = TREE_TYPE (friend_type);
   12679 		}
   12680 	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE
   12681 		       || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
   12682 		{
   12683 		  /* This could be either
   12684 
   12685 		       friend class T::C;
   12686 
   12687 		     when dependent_type_p is false or
   12688 
   12689 		       template <class U> friend class T::C;
   12690 
   12691 		     otherwise.  */
   12692 		  /* Bump processing_template_decl in case this is something like
   12693 		     template <class T> friend struct A<T>::B.  */
   12694 		  ++processing_template_decl;
   12695 		  friend_type = tsubst (friend_type, args,
   12696 					tf_warning_or_error, NULL_TREE);
   12697 		  --processing_template_decl;
   12698 		}
   12699 	      else if (uses_template_parms (friend_type))
   12700 		/* friend class C<T>;  */
   12701 		friend_type = tsubst (friend_type, args,
   12702 				      tf_warning_or_error, NULL_TREE);
   12703 
   12704 	      /* Otherwise it's
   12705 
   12706 		   friend class C;
   12707 
   12708 		 where C is already declared or
   12709 
   12710 		   friend class C<int>;
   12711 
   12712 		 We don't have to do anything in these cases.  */
   12713 
   12714 	      if (friend_type != error_mark_node)
   12715 		make_friend_class (type, friend_type, /*complain=*/false);
   12716 	    }
   12717 	  else
   12718 	    {
   12719 	      /* Build new DECL_FRIENDLIST.  */
   12720 	      tree r;
   12721 
   12722 	      /* The file and line for this declaration, to
   12723 		 assist in error message reporting.  Since we
   12724 		 called push_tinst_level above, we don't need to
   12725 		 restore these.  */
   12726 	      input_location = DECL_SOURCE_LOCATION (t);
   12727 
   12728 	      if (TREE_CODE (t) == TEMPLATE_DECL)
   12729 		{
   12730 		  ++processing_template_decl;
   12731 		  push_deferring_access_checks (dk_no_check);
   12732 		}
   12733 
   12734 	      r = tsubst_friend_function (t, args);
   12735 	      add_friend (type, r, /*complain=*/false);
   12736 	      if (TREE_CODE (t) == TEMPLATE_DECL)
   12737 		{
   12738 		  pop_deferring_access_checks ();
   12739 		  --processing_template_decl;
   12740 		}
   12741 	    }
   12742 	}
   12743     }
   12744 
   12745   if (fn_context)
   12746     {
   12747       /* Restore these before substituting into the lambda capture
   12748 	 initializers.  */
   12749       cp_unevaluated_operand = saved_unevaluated_operand;
   12750       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
   12751     }
   12752 
   12753   /* Set the file and line number information to whatever is given for
   12754      the class itself.  This puts error messages involving generated
   12755      implicit functions at a predictable point, and the same point
   12756      that would be used for non-template classes.  */
   12757   input_location = DECL_SOURCE_LOCATION (typedecl);
   12758 
   12759   unreverse_member_declarations (type);
   12760   finish_struct_1 (type);
   12761   TYPE_BEING_DEFINED (type) = 0;
   12762 
   12763   /* Remember if instantiating this class ran into errors, so we can avoid
   12764      instantiating member functions in limit_bad_template_recursion.  We set
   12765      this flag even if the problem was in another instantiation triggered by
   12766      this one, as that will likely also cause trouble for member functions.  */
   12767   if (errorcount + sorrycount > current_tinst_level->errors)
   12768     CLASSTYPE_ERRONEOUS (type) = true;
   12769 
   12770   /* We don't instantiate default arguments for member functions.  14.7.1:
   12771 
   12772      The implicit instantiation of a class template specialization causes
   12773      the implicit instantiation of the declarations, but not of the
   12774      definitions or default arguments, of the class member functions,
   12775      member classes, static data members and member templates....  */
   12776 
   12777   perform_instantiation_time_access_checks (pattern, args);
   12778   perform_deferred_access_checks (tf_warning_or_error);
   12779 
   12780   /* Now that we've gone through all the members, instantiate those
   12781      marked with attribute used.  We must do this in the context of
   12782      the class -- not the context we pushed from, as that might be
   12783      inside a template and change the behaviour of mark_used.  */
   12784   for (tree x : used)
   12785     mark_used (x);
   12786 
   12787   pop_nested_class ();
   12788   maximum_field_alignment = saved_maximum_field_alignment;
   12789   if (!fn_context)
   12790     pop_from_top_level ();
   12791   pop_tinst_level ();
   12792 
   12793   /* The vtable for a template class can be emitted in any translation
   12794      unit in which the class is instantiated.  When there is no key
   12795      method, however, finish_struct_1 will already have added TYPE to
   12796      the keyed_classes.  */
   12797   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
   12798     vec_safe_push (keyed_classes, type);
   12799 
   12800   return type;
   12801 }
   12802 
   12803 tree
   12804 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
   12805 {
   12806   tree r;
   12807 
   12808   if (!t)
   12809     r = t;
   12810   else if (TYPE_P (t))
   12811     r = tsubst (t, args, complain, in_decl);
   12812   else
   12813     {
   12814       if (!(complain & tf_warning))
   12815 	++c_inhibit_evaluation_warnings;
   12816       r = tsubst_expr (t, args, complain, in_decl);
   12817       if (!(complain & tf_warning))
   12818 	--c_inhibit_evaluation_warnings;
   12819     }
   12820 
   12821   return r;
   12822 }
   12823 
   12824 /* Given a function parameter pack TMPL_PARM and some function parameters
   12825    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
   12826    and set *SPEC_P to point at the next point in the list.  */
   12827 
   12828 tree
   12829 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
   12830 {
   12831   /* Collect all of the extra "packed" parameters into an
   12832      argument pack.  */
   12833   tree argpack;
   12834   tree spec_parm = *spec_p;
   12835   int len;
   12836 
   12837   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
   12838     if (tmpl_parm
   12839 	&& !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
   12840       break;
   12841 
   12842   spec_parm = *spec_p;
   12843   if (len == 1 && DECL_PACK_P (spec_parm))
   12844     {
   12845       /* The instantiation is still a parameter pack; don't wrap it in a
   12846 	 NONTYPE_ARGUMENT_PACK.  */
   12847       argpack = spec_parm;
   12848       spec_parm = DECL_CHAIN (spec_parm);
   12849     }
   12850   else
   12851     {
   12852       /* Fill in PARMVEC with all of the parameters.  */
   12853       tree parmvec = make_tree_vec (len);
   12854       argpack = make_node (NONTYPE_ARGUMENT_PACK);
   12855       for (int i = 0; i < len; i++)
   12856 	{
   12857 	  tree elt = spec_parm;
   12858 	  if (DECL_PACK_P (elt))
   12859 	    elt = make_pack_expansion (elt);
   12860 	  TREE_VEC_ELT (parmvec, i) = elt;
   12861 	  spec_parm = DECL_CHAIN (spec_parm);
   12862 	}
   12863 
   12864       /* Build the argument packs.  */
   12865       ARGUMENT_PACK_ARGS (argpack) = parmvec;
   12866     }
   12867   *spec_p = spec_parm;
   12868 
   12869   return argpack;
   12870 }
   12871 
   12872 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
   12873    NONTYPE_ARGUMENT_PACK.  */
   12874 
   12875 static tree
   12876 make_fnparm_pack (tree spec_parm)
   12877 {
   12878   return extract_fnparm_pack (NULL_TREE, &spec_parm);
   12879 }
   12880 
   12881 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
   12882    pack expansion with no extra args, 2 if it has extra args, or 0
   12883    if it is not a pack expansion.  */
   12884 
   12885 static int
   12886 argument_pack_element_is_expansion_p (tree arg_pack, int i)
   12887 {
   12888   if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
   12889     /* We're being called before this happens in tsubst_pack_expansion.  */
   12890     arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
   12891   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
   12892   if (i >= TREE_VEC_LENGTH (vec))
   12893     return 0;
   12894   tree elt = TREE_VEC_ELT (vec, i);
   12895   if (DECL_P (elt))
   12896     /* A decl pack is itself an expansion.  */
   12897     elt = TREE_TYPE (elt);
   12898   if (!PACK_EXPANSION_P (elt))
   12899     return 0;
   12900   if (PACK_EXPANSION_EXTRA_ARGS (elt))
   12901     return 2;
   12902   return 1;
   12903 }
   12904 
   12905 
   12906 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
   12907 
   12908 static tree
   12909 make_argument_pack_select (tree arg_pack, unsigned index)
   12910 {
   12911   tree aps = make_node (ARGUMENT_PACK_SELECT);
   12912 
   12913   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
   12914   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
   12915 
   12916   return aps;
   12917 }
   12918 
   12919 /*  This is a subroutine of tsubst_pack_expansion.
   12920 
   12921     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
   12922     mechanism to store the (non complete list of) arguments of the
   12923     substitution and return a non substituted pack expansion, in order
   12924     to wait for when we have enough arguments to really perform the
   12925     substitution.  */
   12926 
   12927 static bool
   12928 use_pack_expansion_extra_args_p (tree t,
   12929 				 tree parm_packs,
   12930 				 int arg_pack_len,
   12931 				 bool has_empty_arg)
   12932 {
   12933   if (has_empty_arg
   12934       && PACK_EXPANSION_FORCE_EXTRA_ARGS_P (t))
   12935     return true;
   12936 
   12937   /* If one pack has an expansion and another pack has a normal
   12938      argument or if one pack has an empty argument and an another
   12939      one hasn't then tsubst_pack_expansion cannot perform the
   12940      substitution and need to fall back on the
   12941      PACK_EXPANSION_EXTRA mechanism.  */
   12942   if (parm_packs == NULL_TREE)
   12943     return false;
   12944   else if (has_empty_arg)
   12945     {
   12946       /* If all the actual packs are pack expansions, we can still
   12947 	 subsitute directly.  */
   12948       for (tree p = parm_packs; p; p = TREE_CHAIN (p))
   12949 	{
   12950 	  tree a = TREE_VALUE (p);
   12951 	  if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
   12952 	    a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
   12953 	  a = ARGUMENT_PACK_ARGS (a);
   12954 	  if (TREE_VEC_LENGTH (a) == 1)
   12955 	    a = TREE_VEC_ELT (a, 0);
   12956 	  if (PACK_EXPANSION_P (a))
   12957 	    continue;
   12958 	  return true;
   12959 	}
   12960       return false;
   12961     }
   12962 
   12963   for (int i = 0 ; i < arg_pack_len; ++i)
   12964     {
   12965       bool has_expansion_arg = false;
   12966       bool has_non_expansion_arg = false;
   12967       for (tree parm_pack = parm_packs;
   12968 	   parm_pack;
   12969 	   parm_pack = TREE_CHAIN (parm_pack))
   12970 	{
   12971 	  tree arg = TREE_VALUE (parm_pack);
   12972 
   12973 	  int exp = argument_pack_element_is_expansion_p (arg, i);
   12974 	  if (exp == 2)
   12975 	    /* We can't substitute a pack expansion with extra args into
   12976 	       our pattern.  */
   12977 	    return true;
   12978 	  else if (exp)
   12979 	    has_expansion_arg = true;
   12980 	  else
   12981 	    has_non_expansion_arg = true;
   12982 	}
   12983 
   12984       if (has_expansion_arg && has_non_expansion_arg)
   12985 	{
   12986 	  /* We can get here with:
   12987 
   12988 	      template <class... Ts> struct X {
   12989 		template <class... Us> using Y = Z<void(Ts, Us)...>;
   12990 	      };
   12991 	      template <class A, class... P>
   12992 	      using foo = X<int, int>::Y<A, P...>;
   12993 
   12994 	     where we compare int and A and then the second int and P...,
   12995 	     whose expansion-ness doesn't match, but that's OK.  */
   12996 	  return true;
   12997 	}
   12998     }
   12999   return false;
   13000 }
   13001 
   13002 /* [temp.variadic]/6 says that:
   13003 
   13004        The instantiation of a pack expansion [...]
   13005        produces a list E1,E2, ..., En, where N is the number of elements
   13006        in the pack expansion parameters.
   13007 
   13008    This subroutine of tsubst_pack_expansion produces one of these Ei.
   13009 
   13010    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
   13011    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
   13012    PATTERN, and each TREE_VALUE is its corresponding argument pack.
   13013    INDEX is the index 'i' of the element Ei to produce.  ARGS,
   13014    COMPLAIN, and IN_DECL are the same parameters as for the
   13015    tsubst_pack_expansion function.
   13016 
   13017    The function returns the resulting Ei upon successful completion,
   13018    or error_mark_node.
   13019 
   13020    Note that this function possibly modifies the ARGS parameter, so
   13021    it's the responsibility of the caller to restore it.  */
   13022 
   13023 static tree
   13024 gen_elem_of_pack_expansion_instantiation (tree pattern,
   13025 					  tree parm_packs,
   13026 					  unsigned index,
   13027 					  tree args /* This parm gets
   13028 						       modified.  */,
   13029 					  tsubst_flags_t complain,
   13030 					  tree in_decl)
   13031 {
   13032   tree t;
   13033   bool ith_elem_is_expansion = false;
   13034 
   13035   /* For each parameter pack, change the substitution of the parameter
   13036      pack to the ith argument in its argument pack, then expand the
   13037      pattern.  */
   13038   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
   13039     {
   13040       tree parm = TREE_PURPOSE (pack);
   13041       tree arg_pack = TREE_VALUE (pack);
   13042       tree aps;			/* instance of ARGUMENT_PACK_SELECT.  */
   13043 
   13044       ith_elem_is_expansion |=
   13045 	argument_pack_element_is_expansion_p (arg_pack, index);
   13046 
   13047       /* Select the Ith argument from the pack.  */
   13048       if (TREE_CODE (parm) == PARM_DECL
   13049 	  || VAR_P (parm)
   13050 	  || TREE_CODE (parm) == FIELD_DECL)
   13051 	{
   13052 	  if (index == 0)
   13053 	    {
   13054 	      aps = make_argument_pack_select (arg_pack, index);
   13055 	      if (!mark_used (parm, complain) && !(complain & tf_error))
   13056 		return error_mark_node;
   13057 	      register_local_specialization (aps, parm);
   13058 	    }
   13059 	  else
   13060 	    aps = retrieve_local_specialization (parm);
   13061 	}
   13062       else
   13063 	{
   13064 	  int idx, level;
   13065 	  template_parm_level_and_index (parm, &level, &idx);
   13066 
   13067 	  if (index == 0)
   13068 	    {
   13069 	      aps = make_argument_pack_select (arg_pack, index);
   13070 	      /* Update the corresponding argument.  */
   13071 	      TMPL_ARG (args, level, idx) = aps;
   13072 	    }
   13073 	  else
   13074 	    /* Re-use the ARGUMENT_PACK_SELECT.  */
   13075 	    aps = TMPL_ARG (args, level, idx);
   13076 	}
   13077       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
   13078     }
   13079 
   13080   /* Substitute into the PATTERN with the (possibly altered)
   13081      arguments.  */
   13082   if (pattern == in_decl)
   13083     /* Expanding a fixed parameter pack from
   13084        coerce_template_parameter_pack.  */
   13085     t = tsubst_decl (pattern, args, complain);
   13086   else if (pattern == error_mark_node)
   13087     t = error_mark_node;
   13088   else if (!TYPE_P (pattern))
   13089     t = tsubst_expr (pattern, args, complain, in_decl);
   13090   else
   13091     {
   13092       t = tsubst (pattern, args, complain, in_decl);
   13093       if (is_auto (t) && !ith_elem_is_expansion)
   13094 	/* When expanding the fake auto... pack expansion from add_capture, we
   13095 	   need to mark that the expansion is no longer a pack.  */
   13096 	TEMPLATE_TYPE_PARAMETER_PACK (t) = false;
   13097     }
   13098 
   13099   /*  If the Ith argument pack element is a pack expansion, then
   13100       the Ith element resulting from the substituting is going to
   13101       be a pack expansion as well.  */
   13102   if (ith_elem_is_expansion)
   13103     t = make_pack_expansion (t, complain);
   13104 
   13105   return t;
   13106 }
   13107 
   13108 /* When the unexpanded parameter pack in a fold expression expands to an empty
   13109    sequence, the value of the expression is as follows; the program is
   13110    ill-formed if the operator is not listed in this table.
   13111 
   13112    &&	true
   13113    ||	false
   13114    ,	void()  */
   13115 
   13116 tree
   13117 expand_empty_fold (tree t, tsubst_flags_t complain)
   13118 {
   13119   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
   13120   if (!FOLD_EXPR_MODIFY_P (t))
   13121     switch (code)
   13122       {
   13123       case TRUTH_ANDIF_EXPR:
   13124 	return boolean_true_node;
   13125       case TRUTH_ORIF_EXPR:
   13126 	return boolean_false_node;
   13127       case COMPOUND_EXPR:
   13128 	return void_node;
   13129       default:
   13130 	break;
   13131       }
   13132 
   13133   if (complain & tf_error)
   13134     error_at (location_of (t),
   13135 	      "fold of empty expansion over %O", code);
   13136   return error_mark_node;
   13137 }
   13138 
   13139 /* Given a fold-expression T and a current LEFT and RIGHT operand,
   13140    form an expression that combines the two terms using the
   13141    operator of T. */
   13142 
   13143 static tree
   13144 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
   13145 {
   13146   tree_code code = FOLD_EXPR_OP (t);
   13147 
   13148   tree lookups = templated_operator_saved_lookups (t);
   13149 
   13150   // Handle compound assignment operators.
   13151   if (FOLD_EXPR_MODIFY_P (t))
   13152     return build_x_modify_expr (input_location, left, code, right,
   13153 				lookups, complain);
   13154 
   13155   warning_sentinel s(warn_parentheses);
   13156   switch (code)
   13157     {
   13158     case COMPOUND_EXPR:
   13159       return build_x_compound_expr (input_location, left, right,
   13160 				    lookups, complain);
   13161     default:
   13162       return build_x_binary_op (input_location, code,
   13163                                 left, TREE_CODE (left),
   13164                                 right, TREE_CODE (right),
   13165 				lookups, /*overload=*/NULL,
   13166                                 complain);
   13167     }
   13168 }
   13169 
   13170 /* Substitute ARGS into the pack of a fold expression T. */
   13171 
   13172 static inline tree
   13173 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
   13174 {
   13175   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
   13176 }
   13177 
   13178 /* Substitute ARGS into the pack of a fold expression T. */
   13179 
   13180 static inline tree
   13181 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
   13182 {
   13183   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl);
   13184 }
   13185 
   13186 /* Expand a PACK of arguments into a grouped as left fold.
   13187    Given a pack containing elements A0, A1, ..., An and an
   13188    operator @, this builds the expression:
   13189 
   13190       ((A0 @ A1) @ A2) ... @ An
   13191 
   13192    Note that PACK must not be empty.
   13193 
   13194    The operator is defined by the original fold expression T. */
   13195 
   13196 static tree
   13197 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
   13198 {
   13199   tree left = TREE_VEC_ELT (pack, 0);
   13200   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
   13201     {
   13202       tree right = TREE_VEC_ELT (pack, i);
   13203       left = fold_expression (t, left, right, complain);
   13204     }
   13205   return left;
   13206 }
   13207 
   13208 /* Substitute into a unary left fold expression. */
   13209 
   13210 static tree
   13211 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
   13212                         tree in_decl)
   13213 {
   13214   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
   13215   if (pack == error_mark_node)
   13216     return error_mark_node;
   13217   if (PACK_EXPANSION_P (pack))
   13218     {
   13219       tree r = copy_node (t);
   13220       FOLD_EXPR_PACK (r) = pack;
   13221       return r;
   13222     }
   13223   if (TREE_VEC_LENGTH (pack) == 0)
   13224     return expand_empty_fold (t, complain);
   13225   else
   13226     return expand_left_fold (t, pack, complain);
   13227 }
   13228 
   13229 /* Substitute into a binary left fold expression.
   13230 
   13231    Do ths by building a single (non-empty) vector of argumnts and
   13232    building the expression from those elements. */
   13233 
   13234 static tree
   13235 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
   13236                          tree in_decl)
   13237 {
   13238   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
   13239   if (pack == error_mark_node)
   13240     return error_mark_node;
   13241   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
   13242   if (init == error_mark_node)
   13243     return error_mark_node;
   13244 
   13245   if (PACK_EXPANSION_P (pack))
   13246     {
   13247       tree r = copy_node (t);
   13248       FOLD_EXPR_PACK (r) = pack;
   13249       FOLD_EXPR_INIT (r) = init;
   13250       return r;
   13251     }
   13252 
   13253   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
   13254   TREE_VEC_ELT (vec, 0) = init;
   13255   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
   13256     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
   13257 
   13258   return expand_left_fold (t, vec, complain);
   13259 }
   13260 
   13261 /* Expand a PACK of arguments into a grouped as right fold.
   13262    Given a pack containing elementns A0, A1, ..., and an
   13263    operator @, this builds the expression:
   13264 
   13265       A0@ ... (An-2 @ (An-1 @ An))
   13266 
   13267    Note that PACK must not be empty.
   13268 
   13269    The operator is defined by the original fold expression T. */
   13270 
   13271 tree
   13272 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
   13273 {
   13274   // Build the expression.
   13275   int n = TREE_VEC_LENGTH (pack);
   13276   tree right = TREE_VEC_ELT (pack, n - 1);
   13277   for (--n; n != 0; --n)
   13278     {
   13279       tree left = TREE_VEC_ELT (pack, n - 1);
   13280       right = fold_expression (t, left, right, complain);
   13281     }
   13282   return right;
   13283 }
   13284 
   13285 /* Substitute into a unary right fold expression. */
   13286 
   13287 static tree
   13288 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
   13289                          tree in_decl)
   13290 {
   13291   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
   13292   if (pack == error_mark_node)
   13293     return error_mark_node;
   13294   if (PACK_EXPANSION_P (pack))
   13295     {
   13296       tree r = copy_node (t);
   13297       FOLD_EXPR_PACK (r) = pack;
   13298       return r;
   13299     }
   13300   if (TREE_VEC_LENGTH (pack) == 0)
   13301     return expand_empty_fold (t, complain);
   13302   else
   13303     return expand_right_fold (t, pack, complain);
   13304 }
   13305 
   13306 /* Substitute into a binary right fold expression.
   13307 
   13308    Do ths by building a single (non-empty) vector of arguments and
   13309    building the expression from those elements. */
   13310 
   13311 static tree
   13312 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
   13313                          tree in_decl)
   13314 {
   13315   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
   13316   if (pack == error_mark_node)
   13317     return error_mark_node;
   13318   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
   13319   if (init == error_mark_node)
   13320     return error_mark_node;
   13321 
   13322   if (PACK_EXPANSION_P (pack))
   13323     {
   13324       tree r = copy_node (t);
   13325       FOLD_EXPR_PACK (r) = pack;
   13326       FOLD_EXPR_INIT (r) = init;
   13327       return r;
   13328     }
   13329 
   13330   int n = TREE_VEC_LENGTH (pack);
   13331   tree vec = make_tree_vec (n + 1);
   13332   for (int i = 0; i < n; ++i)
   13333     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
   13334   TREE_VEC_ELT (vec, n) = init;
   13335 
   13336   return expand_right_fold (t, vec, complain);
   13337 }
   13338 
   13339 /* Walk through the pattern of a pack expansion, adding everything in
   13340    local_specializations to a list.  */
   13341 
   13342 class el_data
   13343 {
   13344 public:
   13345   /* Set of variables declared within the pattern.  */
   13346   hash_set<tree> internal;
   13347   /* Set of AST nodes that have been visited by the traversal.  */
   13348   hash_set<tree> visited;
   13349   /* List of local_specializations used within the pattern.  */
   13350   tree extra;
   13351   tsubst_flags_t complain;
   13352   /* True iff we don't want to walk into unevaluated contexts.  */
   13353   bool skip_unevaluated_operands = false;
   13354   /* The unevaluated contexts that we avoided walking.  */
   13355   auto_vec<tree> skipped_trees;
   13356 
   13357   el_data (tsubst_flags_t c)
   13358     : extra (NULL_TREE), complain (c) {}
   13359 };
   13360 static tree
   13361 extract_locals_r (tree *tp, int *walk_subtrees, void *data_)
   13362 {
   13363   el_data &data = *reinterpret_cast<el_data*>(data_);
   13364   tree *extra = &data.extra;
   13365   tsubst_flags_t complain = data.complain;
   13366 
   13367   if (data.skip_unevaluated_operands
   13368       && unevaluated_p (TREE_CODE (*tp)))
   13369     {
   13370       data.skipped_trees.safe_push (*tp);
   13371       *walk_subtrees = 0;
   13372       return NULL_TREE;
   13373     }
   13374 
   13375   if (TYPE_P (*tp) && typedef_variant_p (*tp))
   13376     /* Remember local typedefs (85214).  */
   13377     tp = &TYPE_NAME (*tp);
   13378 
   13379   if (has_extra_args_mechanism_p (*tp))
   13380     /* Assert *_EXTRA_ARGS is empty, because we don't want to walk it and
   13381        potentially see a previously captured local in an evaluated context
   13382        that's really only used in an unevaluated context (PR114303).  This
   13383        means callers of build_extra_args need to clear *_EXTRA_ARGS of the
   13384        outermost tree.  Nested *_EXTRA_ARGS should naturally be empty since
   13385        the outermost (extra-args) tree will intercept any substitution before
   13386        a nested tree can.  */
   13387     gcc_checking_assert (tree_extra_args (*tp) == NULL_TREE
   13388 			/* Except a lambda nested inside an extra-args tree
   13389 			   can have extra args if we deferred partial
   13390 			   substitution into it at template parse time.  But
   13391 			   we don't walk LAMBDA_EXPR_EXTRA_ARGS anyway.  */
   13392 			 || TREE_CODE (*tp) == LAMBDA_EXPR);
   13393 
   13394   if (TREE_CODE (*tp) == DECL_EXPR)
   13395     {
   13396       tree decl = DECL_EXPR_DECL (*tp);
   13397       data.internal.add (decl);
   13398       if (VAR_P (decl)
   13399 	  && DECL_DECOMPOSITION_P (decl)
   13400 	  && TREE_TYPE (decl) != error_mark_node)
   13401 	{
   13402 	  gcc_assert (DECL_NAME (decl) == NULL_TREE);
   13403 	  for (tree decl2 = DECL_CHAIN (decl);
   13404 	       decl2
   13405 	       && VAR_P (decl2)
   13406 	       && DECL_DECOMPOSITION_P (decl2)
   13407 	       && DECL_NAME (decl2)
   13408 	       && TREE_TYPE (decl2) != error_mark_node;
   13409 	       decl2 = DECL_CHAIN (decl2))
   13410 	    {
   13411 	      gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
   13412 	      data.internal.add (decl2);
   13413 	    }
   13414 	}
   13415     }
   13416   else if (TREE_CODE (*tp) == LAMBDA_EXPR)
   13417     {
   13418       /* Since we defer implicit capture, look in the parms and body.  */
   13419       tree fn = lambda_function (*tp);
   13420       cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
   13421 		    &data.visited);
   13422       cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
   13423 		    &data.visited);
   13424     }
   13425   else if (tree spec = retrieve_local_specialization (*tp))
   13426     {
   13427       if (data.internal.contains (*tp))
   13428 	/* Don't mess with variables declared within the pattern.  */
   13429 	return NULL_TREE;
   13430       if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
   13431 	{
   13432 	  /* Maybe pull out the PARM_DECL for a partial instantiation.  */
   13433 	  tree args = ARGUMENT_PACK_ARGS (spec);
   13434 	  if (TREE_VEC_LENGTH (args) == 1)
   13435 	    {
   13436 	      tree elt = TREE_VEC_ELT (args, 0);
   13437 	      if (PACK_EXPANSION_P (elt))
   13438 		elt = PACK_EXPANSION_PATTERN (elt);
   13439 	      if (DECL_PACK_P (elt))
   13440 		spec = elt;
   13441 	    }
   13442 	  if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
   13443 	    {
   13444 	      /* Handle lambda capture here, since we aren't doing any
   13445 		 substitution now, and so tsubst_copy won't call
   13446 		 process_outer_var_ref.  */
   13447 	      tree args = ARGUMENT_PACK_ARGS (spec);
   13448 	      int len = TREE_VEC_LENGTH (args);
   13449 	      for (int i = 0; i < len; ++i)
   13450 		{
   13451 		  tree arg = TREE_VEC_ELT (args, i);
   13452 		  tree carg = arg;
   13453 		  if (outer_automatic_var_p (arg))
   13454 		    carg = process_outer_var_ref (arg, complain);
   13455 		  if (carg != arg)
   13456 		    {
   13457 		      /* Make a new NONTYPE_ARGUMENT_PACK of the capture
   13458 			 proxies.  */
   13459 		      if (i == 0)
   13460 			{
   13461 			  spec = copy_node (spec);
   13462 			  args = copy_node (args);
   13463 			  ARGUMENT_PACK_ARGS (spec) = args;
   13464 			  register_local_specialization (spec, *tp);
   13465 			}
   13466 		      TREE_VEC_ELT (args, i) = carg;
   13467 		    }
   13468 		}
   13469 	    }
   13470 	}
   13471       if (outer_automatic_var_p (spec))
   13472 	spec = process_outer_var_ref (spec, complain);
   13473       *extra = tree_cons (*tp, spec, *extra);
   13474     }
   13475   return NULL_TREE;
   13476 }
   13477 static tree
   13478 extract_local_specs (tree pattern, tsubst_flags_t complain)
   13479 {
   13480   el_data data (complain);
   13481   /* Walk the pattern twice, ignoring unevaluated operands the first time
   13482      around, so that if a local specialization appears in both an evaluated
   13483      and unevaluated context we prefer to process it in the evaluated context
   13484      (since e.g. process_outer_var_ref is a no-op inside an unevaluated
   13485      context).  */
   13486   data.skip_unevaluated_operands = true;
   13487   cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
   13488   /* Now walk the unevaluated contexts we skipped the first time around.  */
   13489   data.skip_unevaluated_operands = false;
   13490   for (tree t : data.skipped_trees)
   13491     {
   13492       data.visited.remove (t);
   13493       cp_walk_tree (&t, extract_locals_r, &data, &data.visited);
   13494     }
   13495   return data.extra;
   13496 }
   13497 
   13498 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
   13499    for use in PACK_EXPANSION_EXTRA_ARGS.  */
   13500 
   13501 tree
   13502 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
   13503 {
   13504   /* Make a copy of the extra arguments so that they won't get changed
   13505      out from under us.  */
   13506   tree extra = preserve_args (copy_template_args (args), /*cow_p=*/false);
   13507   if (local_specializations)
   13508     if (tree locals = extract_local_specs (pattern, complain))
   13509       extra = tree_cons (NULL_TREE, extra, locals);
   13510   return extra;
   13511 }
   13512 
   13513 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
   13514    normal template args to ARGS.  */
   13515 
   13516 tree
   13517 add_extra_args (tree extra, tree args, tsubst_flags_t complain, tree in_decl)
   13518 {
   13519   if (extra && TREE_CODE (extra) == TREE_LIST)
   13520     {
   13521       for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
   13522 	{
   13523 	  /* The partial instantiation involved local declarations collected in
   13524 	     extract_local_specs; map from the general template to our local
   13525 	     context.  */
   13526 	  tree gen = TREE_PURPOSE (elt);
   13527 	  tree inst = TREE_VALUE (elt);
   13528 	  if (DECL_P (inst))
   13529 	    if (tree local = retrieve_local_specialization (inst))
   13530 	      inst = local;
   13531 	  /* else inst is already a full instantiation of the pack.  */
   13532 	  register_local_specialization (inst, gen);
   13533 	  if (is_normal_capture_proxy (gen))
   13534 	    register_local_specialization (inst, DECL_CAPTURED_VARIABLE (gen));
   13535 	}
   13536       gcc_assert (!TREE_PURPOSE (extra));
   13537       extra = TREE_VALUE (extra);
   13538     }
   13539   if (uses_template_parms (extra))
   13540     {
   13541       /* This can happen after dependent substitution into a
   13542 	 requires-expr or a lambda that uses constexpr if.  */
   13543       extra = tsubst_template_args (extra, args, complain, in_decl);
   13544       args = add_outermost_template_args (args, extra);
   13545     }
   13546   else
   13547     args = add_to_template_args (extra, args);
   13548   return args;
   13549 }
   13550 
   13551 /* Substitute ARGS into T, which is an pack expansion
   13552    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
   13553    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
   13554    (if only a partial substitution could be performed) or
   13555    ERROR_MARK_NODE if there was an error.  */
   13556 tree
   13557 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
   13558 		       tree in_decl)
   13559 {
   13560   tree pattern;
   13561   tree pack, packs = NULL_TREE;
   13562   bool unsubstituted_packs = false;
   13563   int i, len = -1;
   13564   tree result;
   13565   bool need_local_specializations = false;
   13566   int levels;
   13567 
   13568   gcc_assert (PACK_EXPANSION_P (t));
   13569   pattern = PACK_EXPANSION_PATTERN (t);
   13570 
   13571   /* Add in any args remembered from an earlier partial instantiation.  */
   13572   args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args, complain, in_decl);
   13573 
   13574   levels = TMPL_ARGS_DEPTH (args);
   13575 
   13576   /* Determine the argument packs that will instantiate the parameter
   13577      packs used in the expansion expression. While we're at it,
   13578      compute the number of arguments to be expanded and make sure it
   13579      is consistent.  */
   13580   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
   13581        pack = TREE_CHAIN (pack))
   13582     {
   13583       tree parm_pack = TREE_VALUE (pack);
   13584       tree arg_pack = NULL_TREE;
   13585       tree orig_arg = NULL_TREE;
   13586       int level = 0;
   13587 
   13588       if (TREE_CODE (parm_pack) == BASES)
   13589 	{
   13590 	  gcc_assert (parm_pack == pattern);
   13591 	  tree type = tsubst (BASES_TYPE (parm_pack), args, complain, in_decl);
   13592 	  if (BASES_DIRECT (parm_pack))
   13593 	    return calculate_direct_bases (type, complain);
   13594 	  else
   13595 	    return calculate_bases (type, complain);
   13596 	}
   13597       else if (builtin_pack_call_p (parm_pack))
   13598 	{
   13599 	  if (parm_pack != pattern)
   13600 	    {
   13601 	      if (complain & tf_error)
   13602 		sorry ("%qE is not the entire pattern of the pack expansion",
   13603 		       parm_pack);
   13604 	      return error_mark_node;
   13605 	    }
   13606 	  return expand_builtin_pack_call (parm_pack, args,
   13607 					   complain, in_decl);
   13608 	}
   13609       else if (TREE_CODE (parm_pack) == PARM_DECL)
   13610 	{
   13611 	  /* We know we have correct local_specializations if this
   13612 	     expansion is at function scope, or if we're dealing with a
   13613 	     local parameter in a requires expression; for the latter,
   13614 	     tsubst_requires_expr set it up appropriately.  */
   13615 	  if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
   13616 	    arg_pack = retrieve_local_specialization (parm_pack);
   13617 	  else
   13618 	    /* We can't rely on local_specializations for a parameter
   13619 	       name used later in a function declaration (such as in a
   13620 	       late-specified return type).  Even if it exists, it might
   13621 	       have the wrong value for a recursive call.  */
   13622 	    need_local_specializations = true;
   13623 
   13624 	  if (!arg_pack)
   13625 	    {
   13626 	      /* This parameter pack was used in an unevaluated context.  Just
   13627 		 make a dummy decl, since it's only used for its type.  */
   13628 	      ++cp_unevaluated_operand;
   13629 	      arg_pack = tsubst_decl (parm_pack, args, complain);
   13630 	      --cp_unevaluated_operand;
   13631 	      if (arg_pack && DECL_PACK_P (arg_pack))
   13632 		/* Partial instantiation of the parm_pack, we can't build
   13633 		   up an argument pack yet.  */
   13634 		arg_pack = NULL_TREE;
   13635 	      else
   13636 		arg_pack = make_fnparm_pack (arg_pack);
   13637 	    }
   13638 	  else if (DECL_PACK_P (arg_pack))
   13639 	    /* This argument pack isn't fully instantiated yet.  */
   13640 	    arg_pack = NULL_TREE;
   13641 	}
   13642       else if (is_capture_proxy (parm_pack))
   13643 	{
   13644 	  arg_pack = retrieve_local_specialization (parm_pack);
   13645 	  if (DECL_PACK_P (arg_pack))
   13646 	    arg_pack = NULL_TREE;
   13647 	}
   13648       else
   13649         {
   13650 	  int idx;
   13651           template_parm_level_and_index (parm_pack, &level, &idx);
   13652           if (level <= levels)
   13653             arg_pack = TMPL_ARG (args, level, idx);
   13654 
   13655 	  if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
   13656 	      && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
   13657 	    arg_pack = NULL_TREE;
   13658         }
   13659 
   13660       orig_arg = arg_pack;
   13661       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
   13662 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
   13663 
   13664       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
   13665 	/* This can only happen if we forget to expand an argument
   13666 	   pack somewhere else. Just return an error, silently.  */
   13667 	{
   13668 	  result = make_tree_vec (1);
   13669 	  TREE_VEC_ELT (result, 0) = error_mark_node;
   13670 	  return result;
   13671 	}
   13672 
   13673       if (arg_pack)
   13674         {
   13675           int my_len =
   13676             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
   13677 
   13678 	  /* Don't bother trying to do a partial substitution with
   13679 	     incomplete packs; we'll try again after deduction.  */
   13680           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
   13681             return t;
   13682 
   13683           if (len < 0)
   13684 	    len = my_len;
   13685 	  else if (len != my_len)
   13686             {
   13687 	      if (!(complain & tf_error))
   13688 		/* Fail quietly.  */;
   13689               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
   13690                 error ("mismatched argument pack lengths while expanding %qT",
   13691                        pattern);
   13692               else
   13693                 error ("mismatched argument pack lengths while expanding %qE",
   13694                        pattern);
   13695               return error_mark_node;
   13696             }
   13697 
   13698           /* Keep track of the parameter packs and their corresponding
   13699              argument packs.  */
   13700           packs = tree_cons (parm_pack, arg_pack, packs);
   13701           TREE_TYPE (packs) = orig_arg;
   13702         }
   13703       else
   13704 	{
   13705 	  /* We can't substitute for this parameter pack.  We use a flag as
   13706 	     well as the missing_level counter because function parameter
   13707 	     packs don't have a level.  */
   13708 	  gcc_assert (processing_template_decl || is_auto (parm_pack)
   13709 		      || args == NULL_TREE);
   13710 	  unsubstituted_packs = true;
   13711 	}
   13712     }
   13713 
   13714   /* If the expansion is just T..., return the matching argument pack, unless
   13715      we need to call convert_from_reference on all the elements.  This is an
   13716      important optimization; see c++/68422.  */
   13717   if (!unsubstituted_packs
   13718       && TREE_PURPOSE (packs) == pattern)
   13719     {
   13720       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
   13721 
   13722       /* If the argument pack is a single pack expansion, pull it out.  */
   13723       if (TREE_VEC_LENGTH (args) == 1
   13724 	  && pack_expansion_args_count (args))
   13725 	{
   13726 	  tree arg = TREE_VEC_ELT (args, 0);
   13727 	  if (PACK_EXPANSION_SIZEOF_P (t)
   13728 	      && !TEMPLATE_PARM_P (PACK_EXPANSION_PATTERN (arg)))
   13729 	    /* Except if this isn't a simple sizeof...(T) which gets sZ
   13730 	       mangling, keep the TREE_VEC to get sP mangling.  */;
   13731 	  else
   13732 	    return TREE_VEC_ELT (args, 0);
   13733 	}
   13734 
   13735       /* Types need no adjustment, nor does sizeof..., and if we still have
   13736 	 some pack expansion args we won't do anything yet.  */
   13737       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
   13738 	  || PACK_EXPANSION_SIZEOF_P (t)
   13739 	  || pack_expansion_args_count (args))
   13740 	return args;
   13741       /* Also optimize expression pack expansions if we can tell that the
   13742 	 elements won't have reference type.  */
   13743       tree type = TREE_TYPE (pattern);
   13744       if (type && !TYPE_REF_P (type)
   13745 	  && !PACK_EXPANSION_P (type)
   13746 	  && !WILDCARD_TYPE_P (type))
   13747 	return args;
   13748       /* Otherwise use the normal path so we get convert_from_reference.  */
   13749     }
   13750 
   13751   /* We cannot expand this expansion expression, because we don't have
   13752      all of the argument packs we need.  */
   13753   if (use_pack_expansion_extra_args_p (t, packs, len, unsubstituted_packs))
   13754     {
   13755       /* We got some full packs, but we can't substitute them in until we
   13756 	 have values for all the packs.  So remember these until then.  */
   13757 
   13758       t = make_pack_expansion (pattern, complain);
   13759       PACK_EXPANSION_EXTRA_ARGS (t)
   13760 	= build_extra_args (pattern, args, complain);
   13761       return t;
   13762     }
   13763 
   13764   /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
   13765      type, so create our own local specializations map; the current map is
   13766      either NULL or (in the case of recursive unification) might have
   13767      bindings that we don't want to use or alter.  */
   13768   local_specialization_stack lss (need_local_specializations
   13769 				  ? lss_blank : lss_nop);
   13770 
   13771   if (unsubstituted_packs)
   13772     {
   13773       /* There were no real arguments, we're just replacing a parameter
   13774 	 pack with another version of itself. Substitute into the
   13775 	 pattern and return a PACK_EXPANSION_*. The caller will need to
   13776 	 deal with that.  */
   13777       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
   13778 	result = tsubst_expr (pattern, args, complain, in_decl);
   13779       else
   13780 	result = tsubst (pattern, args, complain, in_decl);
   13781       result = make_pack_expansion (result, complain);
   13782       PACK_EXPANSION_LOCAL_P (result) = PACK_EXPANSION_LOCAL_P (t);
   13783       PACK_EXPANSION_SIZEOF_P (result) = PACK_EXPANSION_SIZEOF_P (t);
   13784       if (PACK_EXPANSION_AUTO_P (t))
   13785 	{
   13786 	  /* This is a fake auto... pack expansion created in add_capture with
   13787 	     _PACKS that don't appear in the pattern.  Copy one over.  */
   13788 	  packs = PACK_EXPANSION_PARAMETER_PACKS (t);
   13789 	  pack = retrieve_local_specialization (TREE_VALUE (packs));
   13790 	  gcc_checking_assert (DECL_PACK_P (pack));
   13791 	  PACK_EXPANSION_PARAMETER_PACKS (result)
   13792 	    = build_tree_list (NULL_TREE, pack);
   13793 	  PACK_EXPANSION_AUTO_P (result) = true;
   13794 	}
   13795       return result;
   13796     }
   13797 
   13798   gcc_assert (len >= 0);
   13799 
   13800   /* For each argument in each argument pack, substitute into the
   13801      pattern.  */
   13802   result = make_tree_vec (len);
   13803   tree elem_args = copy_template_args (args);
   13804   for (i = 0; i < len; ++i)
   13805     {
   13806       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
   13807 						    i,
   13808 						    elem_args, complain,
   13809 						    in_decl);
   13810       TREE_VEC_ELT (result, i) = t;
   13811       if (t == error_mark_node)
   13812 	{
   13813 	  result = error_mark_node;
   13814 	  break;
   13815 	}
   13816     }
   13817 
   13818   /* Update ARGS to restore the substitution from parameter packs to
   13819      their argument packs.  */
   13820   for (pack = packs; pack; pack = TREE_CHAIN (pack))
   13821     {
   13822       tree parm = TREE_PURPOSE (pack);
   13823 
   13824       if (TREE_CODE (parm) == PARM_DECL
   13825 	  || VAR_P (parm)
   13826 	  || TREE_CODE (parm) == FIELD_DECL)
   13827         register_local_specialization (TREE_TYPE (pack), parm);
   13828       else
   13829         {
   13830           int idx, level;
   13831 
   13832 	  if (TREE_VALUE (pack) == NULL_TREE)
   13833 	    continue;
   13834 
   13835           template_parm_level_and_index (parm, &level, &idx);
   13836 
   13837           /* Update the corresponding argument.  */
   13838           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
   13839             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
   13840               TREE_TYPE (pack);
   13841           else
   13842             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
   13843         }
   13844     }
   13845 
   13846   /* If the dependent pack arguments were such that we end up with only a
   13847      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
   13848   if (len == 1 && TREE_CODE (result) == TREE_VEC
   13849       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
   13850     return TREE_VEC_ELT (result, 0);
   13851 
   13852   return result;
   13853 }
   13854 
   13855 /* Make an argument pack out of the TREE_VEC VEC.  */
   13856 
   13857 static tree
   13858 make_argument_pack (tree vec)
   13859 {
   13860   tree pack;
   13861 
   13862   if (TYPE_P (TREE_VEC_ELT (vec, 0)))
   13863     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
   13864   else
   13865     {
   13866       pack = make_node (NONTYPE_ARGUMENT_PACK);
   13867       TREE_CONSTANT (pack) = 1;
   13868     }
   13869   ARGUMENT_PACK_ARGS (pack) = vec;
   13870   return pack;
   13871 }
   13872 
   13873 /* Return an exact copy of template args T that can be modified
   13874    independently.  */
   13875 
   13876 static tree
   13877 copy_template_args (tree t)
   13878 {
   13879   if (t == error_mark_node)
   13880     return t;
   13881 
   13882   int len = TREE_VEC_LENGTH (t);
   13883   tree new_vec = make_tree_vec (len);
   13884 
   13885   for (int i = 0; i < len; ++i)
   13886     {
   13887       tree elt = TREE_VEC_ELT (t, i);
   13888       if (elt && TREE_CODE (elt) == TREE_VEC)
   13889 	elt = copy_template_args (elt);
   13890       TREE_VEC_ELT (new_vec, i) = elt;
   13891     }
   13892 
   13893   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
   13894     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
   13895 
   13896   return new_vec;
   13897 }
   13898 
   13899 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg.  */
   13900 
   13901 tree
   13902 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
   13903 		      tree in_decl)
   13904 {
   13905   /* This flag is used only during deduction, and we don't expect to
   13906      substitute such ARGUMENT_PACKs.  */
   13907   gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (orig_arg));
   13908 
   13909   /* Substitute into each of the arguments.  */
   13910   tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
   13911 					 args, complain, in_decl);
   13912   if (pack_args == error_mark_node)
   13913     return error_mark_node;
   13914 
   13915   if (pack_args == ARGUMENT_PACK_ARGS (orig_arg))
   13916     return orig_arg;
   13917 
   13918   /* If we're substituting into a generic ARGUMENT_PACK for a variadic
   13919      template parameter, we might be able to avoid allocating a new
   13920      ARGUMENT_PACK and reuse the corresponding ARGUMENT_PACK from ARGS
   13921      if the substituted result is identical to it.  */
   13922   if (tree parm = template_arg_to_parm (orig_arg))
   13923     {
   13924       int level, index;
   13925       template_parm_level_and_index (parm, &level, &index);
   13926       if (TMPL_ARGS_DEPTH (args) >= level)
   13927 	if (tree arg = TMPL_ARG (args, level, index))
   13928 	  if (TREE_CODE (arg) == TREE_CODE (orig_arg)
   13929 	      && ARGUMENT_PACK_ARGS (arg) == pack_args)
   13930 	    {
   13931 	      gcc_assert (!ARGUMENT_PACK_INCOMPLETE_P (arg));
   13932 	      return arg;
   13933 	    }
   13934     }
   13935 
   13936   tree new_arg;
   13937   if (TYPE_P (orig_arg))
   13938     {
   13939       new_arg = cxx_make_type (TREE_CODE (orig_arg));
   13940       SET_TYPE_STRUCTURAL_EQUALITY (new_arg);
   13941     }
   13942   else
   13943     {
   13944       new_arg = make_node (TREE_CODE (orig_arg));
   13945       TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
   13946     }
   13947   ARGUMENT_PACK_ARGS (new_arg) = pack_args;
   13948   return new_arg;
   13949 }
   13950 
   13951 /* Substitute ARGS into the vector or list of template arguments T.  */
   13952 
   13953 tree
   13954 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
   13955 {
   13956   if (t == error_mark_node)
   13957     return error_mark_node;
   13958 
   13959   /* In "sizeof(X<I>)" we need to evaluate "I".  */
   13960   cp_evaluated ev;
   13961 
   13962   const int len = TREE_VEC_LENGTH (t);
   13963   tree *elts = XALLOCAVEC (tree, len);
   13964   int expanded_len_adjust = 0;
   13965 
   13966   /* True iff the substituted result is identical to T.  */
   13967   bool const_subst_p = true;
   13968 
   13969   for (int i = 0; i < len; i++)
   13970     {
   13971       tree orig_arg = TREE_VEC_ELT (t, i);
   13972       tree new_arg;
   13973 
   13974       if (!orig_arg)
   13975 	new_arg = NULL_TREE;
   13976       else if (TREE_CODE (orig_arg) == TREE_VEC)
   13977 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
   13978       else if (PACK_EXPANSION_P (orig_arg))
   13979         {
   13980           /* Substitute into an expansion expression.  */
   13981           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
   13982 
   13983           if (TREE_CODE (new_arg) == TREE_VEC)
   13984             /* Add to the expanded length adjustment the number of
   13985                expanded arguments. We subtract one from this
   13986                measurement, because the argument pack expression
   13987                itself is already counted as 1 in
   13988                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
   13989                the argument pack is empty.  */
   13990             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
   13991         }
   13992       else if (ARGUMENT_PACK_P (orig_arg))
   13993 	new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
   13994       else
   13995 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
   13996 
   13997       if (new_arg == error_mark_node)
   13998 	return error_mark_node;
   13999 
   14000       elts[i] = new_arg;
   14001       if (new_arg != orig_arg)
   14002 	const_subst_p = false;
   14003     }
   14004 
   14005   if (const_subst_p)
   14006     return t;
   14007 
   14008   tree maybe_reuse = NULL_TREE;
   14009 
   14010   /* If ARGS and T are both multi-level, the substituted result may be
   14011      identical to ARGS.  */
   14012   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (t)
   14013       && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
   14014       && TMPL_ARGS_DEPTH (t) == TMPL_ARGS_DEPTH (args))
   14015     maybe_reuse = args;
   14016   /* If T appears to be a vector of generic template arguments, the
   14017      substituted result may be identical to the corresponding level
   14018      from ARGS.  */
   14019   else if (tree parm = template_arg_to_parm (TREE_VEC_ELT (t, 0)))
   14020     {
   14021       int level, index;
   14022       template_parm_level_and_index (parm, &level, &index);
   14023       if (index == 0 && TMPL_ARGS_DEPTH (args) >= level)
   14024 	maybe_reuse = TMPL_ARGS_LEVEL (args, level);
   14025     }
   14026 
   14027   /* If the substituted result is identical to MAYBE_REUSE, return
   14028      it and avoid allocating a new TREE_VEC, as an optimization.  */
   14029   if (maybe_reuse != NULL_TREE
   14030       && TREE_VEC_LENGTH (maybe_reuse) == len
   14031       && std::equal (elts, elts+len, TREE_VEC_BEGIN (maybe_reuse)))
   14032     return maybe_reuse;
   14033 
   14034   /* If T consists of only a pack expansion for which substitution yielded
   14035      a TREE_VEC of the expanded elements, then reuse that TREE_VEC instead
   14036      of effectively making a copy.  */
   14037   if (len == 1
   14038       && PACK_EXPANSION_P (TREE_VEC_ELT (t, 0))
   14039       && TREE_CODE (elts[0]) == TREE_VEC)
   14040     return elts[0];
   14041 
   14042   /* Make space for the expanded arguments coming from template
   14043      argument packs.  */
   14044   tree r = make_tree_vec (len + expanded_len_adjust);
   14045   /* T can contain TREE_VECs. That happens if T contains the
   14046      arguments for a member template.
   14047      In that case each TREE_VEC in T represents a level of template
   14048      arguments, and T won't carry any non defaulted argument count.
   14049      It will rather be the nested TREE_VECs that will carry one.
   14050      In other words, T carries a non defaulted argument count only
   14051      if it doesn't contain any nested TREE_VEC.  */
   14052   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (t))
   14053     {
   14054       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
   14055       count += expanded_len_adjust;
   14056       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (r, count);
   14057     }
   14058 
   14059   int out = 0;
   14060   for (int i = 0; i < len; i++)
   14061     {
   14062       tree orig_arg = TREE_VEC_ELT (t, i);
   14063       if (orig_arg
   14064 	  && PACK_EXPANSION_P (orig_arg)
   14065           && TREE_CODE (elts[i]) == TREE_VEC)
   14066         {
   14067           /* Now expand the template argument pack "in place".  */
   14068 	  for (int idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
   14069 	    TREE_VEC_ELT (r, out) = TREE_VEC_ELT (elts[i], idx);
   14070         }
   14071       else
   14072         {
   14073 	  TREE_VEC_ELT (r, out) = elts[i];
   14074           out++;
   14075         }
   14076     }
   14077   gcc_assert (out == TREE_VEC_LENGTH (r));
   14078 
   14079   return r;
   14080 }
   14081 
   14082 /* Substitute ARGS into one level PARMS of template parameters.  */
   14083 
   14084 static tree
   14085 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
   14086 {
   14087   if (parms == error_mark_node)
   14088     return error_mark_node;
   14089 
   14090   tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
   14091 
   14092   for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
   14093     {
   14094       tree tuple = TREE_VEC_ELT (parms, i);
   14095 
   14096       if (tuple == error_mark_node)
   14097 	continue;
   14098 
   14099       TREE_VEC_ELT (new_vec, i) =
   14100 	tsubst_template_parm (tuple, args, complain);
   14101     }
   14102 
   14103   return new_vec;
   14104 }
   14105 
   14106 /* Return the result of substituting ARGS into the template parameters
   14107    given by PARMS.  If there are m levels of ARGS and m + n levels of
   14108    PARMS, then the result will contain n levels of PARMS.  For
   14109    example, if PARMS is `template <class T> template <class U>
   14110    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
   14111    result will be `template <int*, double, class V>'.  */
   14112 
   14113 static tree
   14114 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
   14115 {
   14116   tree r = NULL_TREE;
   14117   tree* new_parms;
   14118 
   14119   /* When substituting into a template, we must set
   14120      PROCESSING_TEMPLATE_DECL as the template parameters may be
   14121      dependent if they are based on one-another, and the dependency
   14122      predicates are short-circuit outside of templates.  */
   14123   ++processing_template_decl;
   14124 
   14125   for (new_parms = &r;
   14126        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
   14127        new_parms = &(TREE_CHAIN (*new_parms)),
   14128 	 parms = TREE_CHAIN (parms))
   14129     {
   14130       tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
   14131 						  args, complain);
   14132       *new_parms =
   14133 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
   14134 			     - TMPL_ARGS_DEPTH (args)),
   14135 		   new_vec, NULL_TREE);
   14136       TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
   14137 	= TEMPLATE_PARMS_CONSTRAINTS (parms);
   14138     }
   14139 
   14140   --processing_template_decl;
   14141 
   14142   return r;
   14143 }
   14144 
   14145 /* Return the result of substituting ARGS into one template parameter
   14146    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
   14147    parameter and which TREE_PURPOSE is the default argument of the
   14148    template parameter.  */
   14149 
   14150 static tree
   14151 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
   14152 {
   14153   tree default_value, parm_decl;
   14154 
   14155   if (args == NULL_TREE
   14156       || t == NULL_TREE
   14157       || t == error_mark_node)
   14158     return t;
   14159 
   14160   gcc_assert (TREE_CODE (t) == TREE_LIST);
   14161 
   14162   default_value = TREE_PURPOSE (t);
   14163   parm_decl = TREE_VALUE (t);
   14164 
   14165   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
   14166   if (TREE_CODE (parm_decl) == PARM_DECL
   14167       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
   14168     parm_decl = error_mark_node;
   14169   default_value = tsubst_template_arg (default_value, args,
   14170 				       complain, NULL_TREE);
   14171 
   14172   tree r = build_tree_list (default_value, parm_decl);
   14173   TEMPLATE_PARM_CONSTRAINTS (r) = TEMPLATE_PARM_CONSTRAINTS (t);
   14174   return r;
   14175 }
   14176 
   14177 /* Substitute in-place the TEMPLATE_PARM_CONSTRAINTS of each template
   14178    parameter in PARMS for sake of declaration matching.  */
   14179 
   14180 static void
   14181 tsubst_each_template_parm_constraints (tree parms, tree args,
   14182 				       tsubst_flags_t complain)
   14183 {
   14184   ++processing_template_decl;
   14185   for (; parms; parms = TREE_CHAIN (parms))
   14186     {
   14187       tree level = TREE_VALUE (parms);
   14188       for (tree parm : tree_vec_range (level))
   14189 	TEMPLATE_PARM_CONSTRAINTS (parm)
   14190 	  = tsubst_constraint (TEMPLATE_PARM_CONSTRAINTS (parm), args,
   14191 			       complain, NULL_TREE);
   14192     }
   14193   --processing_template_decl;
   14194 }
   14195 
   14196 /* Substitute the ARGS into the indicated aggregate (or enumeration)
   14197    type T.  If T is not an aggregate or enumeration type, it is
   14198    handled as if by tsubst.  IN_DECL is as for tsubst.  If
   14199    ENTERING_SCOPE is nonzero, T is the context for a template which
   14200    we are presently tsubst'ing.  Return the substituted value.  */
   14201 
   14202 static tree
   14203 tsubst_aggr_type (tree t,
   14204 		  tree args,
   14205 		  tsubst_flags_t complain,
   14206 		  tree in_decl,
   14207 		  int entering_scope)
   14208 {
   14209   if (t == NULL_TREE)
   14210     return NULL_TREE;
   14211 
   14212   /* Handle typedefs via tsubst so that they get consistently reused.  */
   14213   if (typedef_variant_p (t))
   14214     {
   14215       t = tsubst (t, args, complain, in_decl);
   14216       if (t == error_mark_node)
   14217 	return error_mark_node;
   14218 
   14219       /* The effect of entering_scope is that for a dependent specialization
   14220 	 A<T>, lookup_template_class prefers to return A's primary template
   14221 	 type instead of the implicit instantiation.  So when entering_scope,
   14222 	 we mirror this behavior by inspecting TYPE_CANONICAL appropriately,
   14223 	 taking advantage of the fact that lookup_template_class links the two
   14224 	 types by setting TYPE_CANONICAL of the latter to the former.  */
   14225       if (entering_scope
   14226 	  && CLASS_TYPE_P (t)
   14227 	  && dependent_type_p (t)
   14228 	  && TYPE_TEMPLATE_INFO (t)
   14229 	  && TYPE_CANONICAL (t) == TREE_TYPE (TYPE_TI_TEMPLATE (t)))
   14230 	t = TYPE_CANONICAL (t);
   14231 
   14232       return t;
   14233     }
   14234 
   14235   switch (TREE_CODE (t))
   14236     {
   14237       case RECORD_TYPE:
   14238       case ENUMERAL_TYPE:
   14239       case UNION_TYPE:
   14240 	return tsubst_aggr_type_1 (t, args, complain, in_decl, entering_scope);
   14241 
   14242       default:
   14243 	return tsubst (t, args, complain, in_decl);
   14244     }
   14245 }
   14246 
   14247 /* The part of tsubst_aggr_type that's shared with the RECORD_, UNION_
   14248    and ENUMERAL_TYPE cases of tsubst.  */
   14249 
   14250 static tree
   14251 tsubst_aggr_type_1 (tree t,
   14252 		    tree args,
   14253 		    tsubst_flags_t complain,
   14254 		    tree in_decl,
   14255 		    int entering_scope)
   14256 {
   14257   if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
   14258     {
   14259       complain &= ~tf_qualifying_scope;
   14260 
   14261       /* Figure out what arguments are appropriate for the
   14262 	 type we are trying to find.  For example, given:
   14263 
   14264 	   template <class T> struct S;
   14265 	   template <class T, class U> void f(T, U) { S<U> su; }
   14266 
   14267 	 and supposing that we are instantiating f<int, double>,
   14268 	 then our ARGS will be {int, double}, but, when looking up
   14269 	 S we only want {double}.  */
   14270       tree argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
   14271 					  complain, in_decl);
   14272       if (argvec == error_mark_node)
   14273 	return error_mark_node;
   14274 
   14275       tree r = lookup_template_class (t, argvec, in_decl, NULL_TREE,
   14276 				      entering_scope, complain);
   14277       return cp_build_qualified_type (r, cp_type_quals (t), complain);
   14278     }
   14279   else
   14280     /* This is not a template type, so there's nothing to do.  */
   14281     return t;
   14282 }
   14283 
   14284 /* Map from a FUNCTION_DECL to a vec of default argument instantiations,
   14285    indexed in reverse order of the parameters.  */
   14286 
   14287 static GTY((cache)) hash_table<tree_vec_map_cache_hasher> *defarg_inst;
   14288 
   14289 /* Return a reference to the vec* of defarg insts for FN.  */
   14290 
   14291 static vec<tree,va_gc> *&
   14292 defarg_insts_for (tree fn)
   14293 {
   14294   if (!defarg_inst)
   14295     defarg_inst = hash_table<tree_vec_map_cache_hasher>::create_ggc (13);
   14296   tree_vec_map in = { { fn }, nullptr };
   14297   tree_vec_map **slot
   14298     = defarg_inst->find_slot_with_hash (&in, DECL_UID (fn), INSERT);
   14299   if (!*slot)
   14300     {
   14301       *slot = ggc_alloc<tree_vec_map> ();
   14302       **slot = in;
   14303     }
   14304   return (*slot)->to;
   14305 }
   14306 
   14307 /* Substitute into the default argument ARG (a default argument for
   14308    FN), which has the indicated TYPE.  */
   14309 
   14310 tree
   14311 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
   14312 			 tsubst_flags_t complain)
   14313 {
   14314   int errs = errorcount + sorrycount;
   14315 
   14316   /* This can happen in invalid code.  */
   14317   if (TREE_CODE (arg) == DEFERRED_PARSE)
   14318     return arg;
   14319 
   14320   /* Shortcut {}.  */
   14321   if (BRACE_ENCLOSED_INITIALIZER_P (arg)
   14322       && CONSTRUCTOR_NELTS (arg) == 0)
   14323     return arg;
   14324 
   14325   tree parm = FUNCTION_FIRST_USER_PARM (fn);
   14326   parm = chain_index (parmnum, parm);
   14327   tree parmtype = TREE_TYPE (parm);
   14328   if (DECL_BY_REFERENCE (parm))
   14329     parmtype = TREE_TYPE (parmtype);
   14330   if (parmtype == error_mark_node)
   14331     return error_mark_node;
   14332 
   14333   gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
   14334 
   14335   /* Remember the location of the pointer to the vec rather than the location
   14336      of the particular element, in case the vec grows in tsubst_expr.  */
   14337   vec<tree,va_gc> *&defs = defarg_insts_for (fn);
   14338   /* Index in reverse order to avoid allocating space for initial parameters
   14339      that don't have default arguments.  */
   14340   unsigned ridx = list_length (parm);
   14341   if (vec_safe_length (defs) < ridx)
   14342     vec_safe_grow_cleared (defs, ridx);
   14343   else if (tree inst = (*defs)[ridx - 1])
   14344     return inst;
   14345 
   14346   /* This default argument came from a template.  Instantiate the
   14347      default argument here, not in tsubst.  In the case of
   14348      something like:
   14349 
   14350        template <class T>
   14351        struct S {
   14352 	 static T t();
   14353 	 void f(T = t());
   14354        };
   14355 
   14356      we must be careful to do name lookup in the scope of S<T>,
   14357      rather than in the current class.  */
   14358   push_to_top_level ();
   14359   push_access_scope (fn);
   14360   push_deferring_access_checks (dk_no_deferred);
   14361   /* So in_immediate_context knows this is a default argument.  */
   14362   begin_scope (sk_function_parms, fn);
   14363   start_lambda_scope (parm);
   14364 
   14365   /* The default argument expression may cause implicitly defined
   14366      member functions to be synthesized, which will result in garbage
   14367      collection.  We must treat this situation as if we were within
   14368      the body of function so as to avoid collecting live data on the
   14369      stack.  */
   14370   ++function_depth;
   14371   arg = tsubst_expr (arg, DECL_TI_ARGS (fn), complain, NULL_TREE);
   14372   --function_depth;
   14373 
   14374   finish_lambda_scope ();
   14375 
   14376   /* Make sure the default argument is reasonable.  */
   14377   arg = check_default_argument (type, arg, complain);
   14378 
   14379   if (errorcount+sorrycount > errs
   14380       && (complain & tf_warning_or_error))
   14381     inform (input_location,
   14382 	    "  when instantiating default argument for call to %qD", fn);
   14383 
   14384   leave_scope ();
   14385   pop_deferring_access_checks ();
   14386   pop_access_scope (fn);
   14387   pop_from_top_level ();
   14388 
   14389   if (arg != error_mark_node && !cp_unevaluated_operand)
   14390     (*defs)[ridx - 1] = arg;
   14391 
   14392   return arg;
   14393 }
   14394 
   14395 /* Substitute into all the default arguments for FN.  */
   14396 
   14397 static void
   14398 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
   14399 {
   14400   tree arg;
   14401   tree tmpl_args;
   14402 
   14403   tmpl_args = DECL_TI_ARGS (fn);
   14404 
   14405   /* If this function is not yet instantiated, we certainly don't need
   14406      its default arguments.  */
   14407   if (uses_template_parms (tmpl_args))
   14408     return;
   14409   /* Don't do this again for clones.  */
   14410   if (DECL_CLONED_FUNCTION_P (fn))
   14411     return;
   14412 
   14413   int i = 0;
   14414   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
   14415        arg;
   14416        arg = TREE_CHAIN (arg), ++i)
   14417     if (TREE_PURPOSE (arg))
   14418       TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
   14419 						    TREE_VALUE (arg),
   14420 						    TREE_PURPOSE (arg),
   14421 						    complain);
   14422 }
   14423 
   14424 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier.  */
   14425 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
   14426 
   14427 /* Store a pair to EXPLICIT_SPECIFIER_MAP.  */
   14428 
   14429 void
   14430 store_explicit_specifier (tree v, tree t)
   14431 {
   14432   if (!explicit_specifier_map)
   14433     explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
   14434   DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
   14435   explicit_specifier_map->put (v, t);
   14436 }
   14437 
   14438 /* Lookup an element in EXPLICIT_SPECIFIER_MAP.  */
   14439 
   14440 tree
   14441 lookup_explicit_specifier (tree v)
   14442 {
   14443   return *explicit_specifier_map->get (v);
   14444 }
   14445 
   14446 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
   14447    FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
   14448    are ARG_TYPES, and exception specification is RAISES, and otherwise is
   14449    identical to T.  */
   14450 
   14451 static tree
   14452 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
   14453 				 tree raises, tsubst_flags_t complain)
   14454 {
   14455   gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
   14456 
   14457   tree new_type;
   14458   if (TREE_CODE (t) == FUNCTION_TYPE)
   14459     {
   14460       new_type = build_function_type (return_type, arg_types);
   14461       new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
   14462     }
   14463   else
   14464     {
   14465       tree r = TREE_TYPE (TREE_VALUE (arg_types));
   14466       /* Don't pick up extra function qualifiers from the basetype.  */
   14467       r = cp_build_qualified_type (r, type_memfn_quals (t), complain);
   14468       if (! MAYBE_CLASS_TYPE_P (r))
   14469 	{
   14470 	  /* [temp.deduct]
   14471 
   14472 	     Type deduction may fail for any of the following
   14473 	     reasons:
   14474 
   14475 	     -- Attempting to create "pointer to member of T" when T
   14476 	     is not a class type.  */
   14477 	  if (complain & tf_error)
   14478 	    error ("creating pointer to member function of non-class type %qT",
   14479 		   r);
   14480 	  return error_mark_node;
   14481 	}
   14482 
   14483       new_type = build_method_type_directly (r, return_type,
   14484 					     TREE_CHAIN (arg_types));
   14485     }
   14486   new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
   14487 
   14488   cp_ref_qualifier rqual = type_memfn_rqual (t);
   14489   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
   14490   return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
   14491 }
   14492 
   14493 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
   14494    each of its formal parameters.  If there is a disagreement then rebuild
   14495    DECL's function type according to its formal parameter types, as part of a
   14496    resolution for Core issues 1001/1322.  */
   14497 
   14498 static void
   14499 maybe_rebuild_function_decl_type (tree decl)
   14500 {
   14501   bool function_type_needs_rebuilding = false;
   14502   if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
   14503     {
   14504       tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
   14505       while (parm_type_list && parm_type_list != void_list_node)
   14506 	{
   14507 	  tree parm_type = TREE_VALUE (parm_type_list);
   14508 	  tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
   14509 	  if (!same_type_p (parm_type, formal_parm_type_unqual))
   14510 	    {
   14511 	      function_type_needs_rebuilding = true;
   14512 	      break;
   14513 	    }
   14514 
   14515 	  parm_list = DECL_CHAIN (parm_list);
   14516 	  parm_type_list = TREE_CHAIN (parm_type_list);
   14517 	}
   14518     }
   14519 
   14520   if (!function_type_needs_rebuilding)
   14521     return;
   14522 
   14523   const tree fntype = TREE_TYPE (decl);
   14524   tree parm_list = DECL_ARGUMENTS (decl);
   14525   tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
   14526   tree new_parm_type_list = NULL_TREE;
   14527   tree *q = &new_parm_type_list;
   14528   for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
   14529     {
   14530       *q = copy_node (old_parm_type_list);
   14531       parm_list = DECL_CHAIN (parm_list);
   14532       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
   14533       q = &TREE_CHAIN (*q);
   14534     }
   14535   while (old_parm_type_list && old_parm_type_list != void_list_node)
   14536     {
   14537       *q = copy_node (old_parm_type_list);
   14538       tree *new_parm_type = &TREE_VALUE (*q);
   14539       tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
   14540       if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
   14541 	*new_parm_type = formal_parm_type_unqual;
   14542 
   14543       parm_list = DECL_CHAIN (parm_list);
   14544       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
   14545       q = &TREE_CHAIN (*q);
   14546     }
   14547   if (old_parm_type_list == void_list_node)
   14548     *q = void_list_node;
   14549 
   14550   TREE_TYPE (decl)
   14551     = rebuild_function_or_method_type (fntype,
   14552 				       TREE_TYPE (fntype), new_parm_type_list,
   14553 				       TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
   14554 }
   14555 
   14556 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
   14557 
   14558 static tree
   14559 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
   14560 		      tree lambda_fntype, bool use_spec_table = true)
   14561 {
   14562   tree gen_tmpl = NULL_TREE, argvec = NULL_TREE;
   14563   hashval_t hash = 0;
   14564   tree in_decl = t;
   14565 
   14566   /* Nobody should be tsubst'ing into non-template functions.  */
   14567   gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE
   14568 	      || DECL_LOCAL_DECL_P (t));
   14569 
   14570   if (DECL_LOCAL_DECL_P (t))
   14571     {
   14572       if (tree spec = retrieve_local_specialization (t))
   14573 	return spec;
   14574     }
   14575   else if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
   14576     {
   14577       /* If T is not dependent, just return it.  */
   14578       if (!uses_template_parms (DECL_TI_ARGS (t))
   14579 	  && !LAMBDA_FUNCTION_P (t))
   14580 	return t;
   14581 
   14582       /* A non-templated friend doesn't get DECL_TEMPLATE_INFO.  */
   14583       if (non_templated_friend_p (t))
   14584 	goto friend_case;
   14585 
   14586       /* Calculate the most general template of which R is a
   14587 	 specialization.  */
   14588       gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
   14589 
   14590       /* We're substituting a lambda function under tsubst_lambda_expr but not
   14591 	 directly from it; find the matching function we're already inside.
   14592 	 But don't do this if T is a generic lambda with a single level of
   14593 	 template parms, as in that case we're doing a normal instantiation. */
   14594       if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
   14595 	  && (!generic_lambda_fn_p (t)
   14596 	      || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
   14597 	return enclosing_instantiation_of (t);
   14598 
   14599       /* Calculate the complete set of arguments used to
   14600 	 specialize R.  */
   14601       if (use_spec_table && !lambda_fntype)
   14602 	{
   14603 	  argvec = tsubst_template_args (DECL_TI_ARGS
   14604 					 (DECL_TEMPLATE_RESULT
   14605 					  (DECL_TI_TEMPLATE (t))),
   14606 					 args, complain, in_decl);
   14607 	  if (argvec == error_mark_node)
   14608 	    return error_mark_node;
   14609 
   14610 	  /* Check to see if we already have this specialization.  */
   14611 	  hash = spec_hasher::hash (gen_tmpl, argvec);
   14612 	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
   14613 	    /* The spec for these args might be a partial instantiation of the
   14614 	       template, but here what we want is the FUNCTION_DECL.  */
   14615 	    return STRIP_TEMPLATE (spec);
   14616 	}
   14617       else
   14618 	argvec = args;
   14619     }
   14620   else
   14621     {
   14622       /* This special case arises when we have something like this:
   14623 
   14624 	 template <class T> struct S {
   14625 	   friend void f<int>(int, double);
   14626 	 };
   14627 
   14628 	 Here, the DECL_TI_TEMPLATE for the friend declaration
   14629 	 will be an IDENTIFIER_NODE.  We are being called from
   14630 	 tsubst_friend_function, and we want only to create a
   14631 	 new decl (R) with appropriate types so that we can call
   14632 	 determine_specialization.  */
   14633     friend_case:
   14634       gen_tmpl = NULL_TREE;
   14635       argvec = NULL_TREE;
   14636     }
   14637 
   14638   tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
   14639 		  : NULL_TREE);
   14640   tree ctx = closure ? closure : DECL_CONTEXT (t);
   14641   bool member = ctx && TYPE_P (ctx);
   14642 
   14643   /* If this is a static or xobj lambda, remove the 'this' pointer added in
   14644      tsubst_lambda_expr now that we know the closure type.  */
   14645   if (lambda_fntype && !DECL_IOBJ_MEMBER_FUNCTION_P (t))
   14646     lambda_fntype = static_fn_type (lambda_fntype);
   14647 
   14648   if (member && !closure)
   14649     ctx = tsubst_aggr_type (ctx, args,
   14650 			    complain, t, /*entering_scope=*/1);
   14651 
   14652   tree type = (lambda_fntype ? lambda_fntype
   14653 	       : tsubst (TREE_TYPE (t), args,
   14654 			 complain | tf_fndecl_type, in_decl));
   14655   if (type == error_mark_node)
   14656     return error_mark_node;
   14657 
   14658   /* If we hit excessive deduction depth, the type is bogus even if
   14659      it isn't error_mark_node, so don't build a decl.  */
   14660   if (excessive_deduction_depth)
   14661     return error_mark_node;
   14662 
   14663   /* We do NOT check for matching decls pushed separately at this
   14664      point, as they may not represent instantiations of this
   14665      template, and in any case are considered separate under the
   14666      discrete model.  */
   14667   tree r = copy_decl (t);
   14668   DECL_USE_TEMPLATE (r) = 0;
   14669   TREE_TYPE (r) = type;
   14670   /* Clear out the mangled name and RTL for the instantiation.  */
   14671   SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
   14672   SET_DECL_RTL (r, NULL);
   14673   /* Leave DECL_INITIAL set on deleted instantiations.  */
   14674   if (!DECL_DELETED_FN (r))
   14675     DECL_INITIAL (r) = NULL_TREE;
   14676   DECL_CONTEXT (r) = ctx;
   14677   set_instantiating_module (r);
   14678 
   14679   /* Handle explicit(dependent-expr).  */
   14680   if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
   14681     {
   14682       tree spec = lookup_explicit_specifier (t);
   14683       spec = tsubst_expr (spec, args, complain, in_decl);
   14684       spec = build_explicit_specifier (spec, complain);
   14685       if (spec == error_mark_node)
   14686 	return error_mark_node;
   14687       if (instantiation_dependent_expression_p (spec))
   14688 	store_explicit_specifier (r, spec);
   14689       else
   14690 	{
   14691 	  DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
   14692 	  DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (r) = false;
   14693 	}
   14694     }
   14695 
   14696   /* OpenMP UDRs have the only argument a reference to the declared
   14697      type.  We want to diagnose if the declared type is a reference,
   14698      which is invalid, but as references to references are usually
   14699      quietly merged, diagnose it here.  */
   14700   if (DECL_OMP_DECLARE_REDUCTION_P (t))
   14701     {
   14702       tree argtype
   14703 	= TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
   14704       argtype = tsubst (argtype, args, complain, in_decl);
   14705       if (TYPE_REF_P (argtype))
   14706 	error_at (DECL_SOURCE_LOCATION (t),
   14707 		  "reference type %qT in "
   14708 		  "%<#pragma omp declare reduction%>", argtype);
   14709       if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
   14710 	DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
   14711 					  argtype);
   14712     }
   14713 
   14714   if (member && DECL_CONV_FN_P (r))
   14715     /* Type-conversion operator.  Reconstruct the name, in
   14716        case it's the name of one of the template's parameters.  */
   14717     DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
   14718 
   14719   tree parms = DECL_ARGUMENTS (t);
   14720   if (closure && DECL_IOBJ_MEMBER_FUNCTION_P (t))
   14721     parms = DECL_CHAIN (parms);
   14722   parms = tsubst (parms, args, complain, t);
   14723   for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
   14724     DECL_CONTEXT (parm) = r;
   14725   if (closure && DECL_IOBJ_MEMBER_FUNCTION_P (t))
   14726     {
   14727       tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
   14728       DECL_NAME (tparm) = closure_identifier;
   14729       DECL_CHAIN (tparm) = parms;
   14730       parms = tparm;
   14731     }
   14732   DECL_ARGUMENTS (r) = parms;
   14733   DECL_RESULT (r) = NULL_TREE;
   14734 
   14735   maybe_rebuild_function_decl_type (r);
   14736 
   14737   TREE_STATIC (r) = 0;
   14738   TREE_PUBLIC (r) = TREE_PUBLIC (t);
   14739   DECL_EXTERNAL (r) = 1;
   14740   /* If this is an instantiation of a function with internal
   14741      linkage, we already know what object file linkage will be
   14742      assigned to the instantiation.  */
   14743   DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
   14744   DECL_DEFER_OUTPUT (r) = 0;
   14745   DECL_CHAIN (r) = NULL_TREE;
   14746   DECL_PENDING_INLINE_INFO (r) = 0;
   14747   DECL_PENDING_INLINE_P (r) = 0;
   14748   DECL_SAVED_TREE (r) = NULL_TREE;
   14749   DECL_STRUCT_FUNCTION (r) = NULL;
   14750   TREE_USED (r) = 0;
   14751   /* We'll re-clone as appropriate in instantiate_template.  */
   14752   DECL_CLONED_FUNCTION (r) = NULL_TREE;
   14753 
   14754   /* If we aren't complaining now, return on error before we register
   14755      the specialization so that we'll complain eventually.  */
   14756   if ((complain & tf_error) == 0
   14757       && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
   14758       && !grok_op_properties (r, /*complain=*/false))
   14759     return error_mark_node;
   14760 
   14761   /* If we are looking at an xobj lambda, we might need to check the type of
   14762      its xobj parameter.  */
   14763   if (LAMBDA_FUNCTION_P (r) && DECL_XOBJ_MEMBER_FUNCTION_P (r))
   14764     {
   14765       tree closure_obj = DECL_CONTEXT (r);
   14766       tree lambda_expr = CLASSTYPE_LAMBDA_EXPR (closure_obj);
   14767       tree obj_param = TREE_TYPE (DECL_ARGUMENTS (r));
   14768 
   14769       if (!(LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (lambda_expr) != CPLD_NONE
   14770 	    || LAMBDA_EXPR_CAPTURE_LIST (lambda_expr)))
   14771 	/* If a lambda has an empty capture clause, an xobj parameter of
   14772 	   unrelated type is not an error.  */;
   14773       else if (dependent_type_p (obj_param))
   14774 	/* If we are coming from tsubst_lambda_expr we might not have
   14775 	   substituted into our xobj parameter yet.  We can't error out until
   14776 	   we know what the type really is so do nothing...
   14777 	   ...but if we are instantiating the call op for real and we don't
   14778 	   have a real type then something has gone incredibly wrong.  */
   14779 	gcc_assert (lambda_fntype);
   14780       else
   14781 	{
   14782 	  /* We have a lambda with captures, and know the type of the xobj
   14783 	     parameter, time to check it.  */
   14784 	  tree obj_param_type = TYPE_MAIN_VARIANT (non_reference (obj_param));
   14785 	  if (!same_or_base_type_p (closure_obj, obj_param_type))
   14786 	    {
   14787 	      /* This error does not emit when the lambda's call operator
   14788 		 template is instantiated by taking its address, such as in
   14789 		 the following case:
   14790 
   14791 		 auto f = [x = 0](this auto&&){};
   14792 		 int (*fp)(int&) = &decltype(f)::operator();
   14793 
   14794 		 It only emits when explicitly calling the call operator with
   14795 		 an explicit template parameter:
   14796 
   14797 		 template<typename T>
   14798 		 struct S : T {
   14799 		   using T::operator();
   14800 		   operator int() const {return {};}
   14801 		 };
   14802 
   14803 		 auto s = S{[x = 0](this auto&&) {}};
   14804 		 s.operator()<int>();
   14805 
   14806 		 This is due to resolve_address_of_overloaded_function being
   14807 		 deficient at reporting candidates when overload resolution
   14808 		 fails.
   14809 
   14810 		 This diagnostic will be active in the first case if/when
   14811 		 resolve_address_of_overloaded_function is fixed to properly
   14812 		 emit candidates upon failure to resolve to an overload.  */
   14813 	      if (complain & tf_error)
   14814 		error ("a lambda with captures may not have an explicit "
   14815 		       "object parameter of an unrelated type");
   14816 	      return error_mark_node;
   14817 	    }
   14818 	}
   14819     }
   14820 
   14821   /* Associate the constraints directly with the instantiation. We
   14822      don't substitute through the constraints; that's only done when
   14823      they are checked.  */
   14824   if (tree ci = get_constraints (t))
   14825     set_constraints (r, ci);
   14826 
   14827   if (DECL_FRIEND_CONTEXT (t))
   14828     SET_DECL_FRIEND_CONTEXT (r,
   14829 			     tsubst (DECL_FRIEND_CONTEXT (t),
   14830 				     args, complain, in_decl));
   14831 
   14832   if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
   14833 				       args, complain, in_decl))
   14834     return error_mark_node;
   14835 
   14836   /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
   14837      this in the special friend case mentioned above where
   14838      GEN_TMPL is NULL.  */
   14839   if (gen_tmpl && !closure)
   14840     {
   14841       DECL_TEMPLATE_INFO (r)
   14842 	= build_template_info (gen_tmpl, argvec);
   14843       SET_DECL_IMPLICIT_INSTANTIATION (r);
   14844 
   14845       if (use_spec_table)
   14846 	{
   14847 	  tree new_r
   14848 	    = register_specialization (r, gen_tmpl, argvec, false, hash);
   14849 	  if (new_r != r)
   14850 	    /* We instantiated this while substituting into
   14851 	       the type earlier (template/friend54.C).  */
   14852 	    return new_r;
   14853 	}
   14854 
   14855       /* We're not supposed to instantiate default arguments
   14856 	 until they are called, for a template.  But, for a
   14857 	 declaration like:
   14858 
   14859 	 template <class T> void f ()
   14860 	 { extern void g(int i = T()); }
   14861 
   14862 	 we should do the substitution when the template is
   14863 	 instantiated.  We handle the member function case in
   14864 	 instantiate_class_template since the default arguments
   14865 	 might refer to other members of the class.  */
   14866       if (!member
   14867 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
   14868 	  && !uses_template_parms (argvec))
   14869 	tsubst_default_arguments (r, complain);
   14870     }
   14871   else if (DECL_LOCAL_DECL_P (r))
   14872     {
   14873       if (!cp_unevaluated_operand)
   14874 	register_local_specialization (r, t);
   14875     }
   14876   else
   14877     DECL_TEMPLATE_INFO (r) = NULL_TREE;
   14878 
   14879   /* Copy the list of befriending classes.  */
   14880   for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
   14881        *friends;
   14882        friends = &TREE_CHAIN (*friends))
   14883     {
   14884       *friends = copy_node (*friends);
   14885       TREE_VALUE (*friends)
   14886 	= tsubst (TREE_VALUE (*friends), args, complain, in_decl);
   14887     }
   14888 
   14889   if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
   14890     {
   14891       maybe_retrofit_in_chrg (r);
   14892       if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
   14893 	return error_mark_node;
   14894       /* If this is an instantiation of a member template, clone it.
   14895 	 If it isn't, that'll be handled by
   14896 	 clone_constructors_and_destructors.  */
   14897       if (gen_tmpl && PRIMARY_TEMPLATE_P (gen_tmpl))
   14898 	clone_cdtor (r, /*update_methods=*/false);
   14899     }
   14900   else if ((complain & tf_error) != 0
   14901 	   && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
   14902 	   && !grok_op_properties (r, /*complain=*/true))
   14903     return error_mark_node;
   14904 
   14905   /* Possibly limit visibility based on template args.  */
   14906   DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
   14907   if (DECL_VISIBILITY_SPECIFIED (t))
   14908     {
   14909       DECL_VISIBILITY_SPECIFIED (r) = 0;
   14910       DECL_ATTRIBUTES (r)
   14911 	= remove_attribute ("visibility", DECL_ATTRIBUTES (r));
   14912     }
   14913   determine_visibility (r);
   14914   if (DECL_SECTION_NAME (t))
   14915     set_decl_section_name (r, t);
   14916   if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
   14917       && COMPLETE_TYPE_P (DECL_CONTEXT (r))
   14918       && !processing_template_decl)
   14919     defaulted_late_check (r);
   14920 
   14921   if (flag_openmp)
   14922     if (tree attr = lookup_attribute ("omp declare variant base",
   14923 				      DECL_ATTRIBUTES (r)))
   14924       omp_declare_variant_finalize (r, attr);
   14925 
   14926   return r;
   14927 }
   14928 
   14929 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
   14930 
   14931 static tree
   14932 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
   14933 		      tree lambda_fntype, tree lambda_tparms)
   14934 {
   14935   /* We can get here when processing a member function template,
   14936      member class template, or template template parameter.  */
   14937   tree decl = DECL_TEMPLATE_RESULT (t);
   14938   tree in_decl = t;
   14939   tree spec;
   14940   tree tmpl_args;
   14941   tree full_args = NULL_TREE;
   14942   tree r;
   14943   hashval_t hash = 0;
   14944 
   14945   if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
   14946     {
   14947       /* Template template parameter is treated here.  */
   14948       tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   14949       if (new_type == error_mark_node)
   14950 	r = error_mark_node;
   14951       /* If we get a real template back, return it.  This can happen in
   14952 	 the context of most_specialized_partial_spec.  */
   14953       else if (TREE_CODE (new_type) == TEMPLATE_DECL)
   14954 	r = new_type;
   14955       else
   14956 	/* The new TEMPLATE_DECL was built in
   14957 	   reduce_template_parm_level.  */
   14958 	r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
   14959       return r;
   14960     }
   14961 
   14962   if (!lambda_fntype)
   14963     {
   14964       /* We might already have an instance of this template.
   14965 	 The ARGS are for the surrounding class type, so the
   14966 	 full args contain the tsubst'd args for the context,
   14967 	 plus the innermost args from the template decl.  */
   14968       tmpl_args = DECL_CLASS_TEMPLATE_P (t)
   14969 	? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
   14970 	: DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
   14971       /* Because this is a template, the arguments will still be
   14972 	 dependent, even after substitution.  If
   14973 	 PROCESSING_TEMPLATE_DECL is not set, the dependency
   14974 	 predicates will short-circuit.  */
   14975       ++processing_template_decl;
   14976       full_args = tsubst_template_args (tmpl_args, args,
   14977 					complain, in_decl);
   14978       --processing_template_decl;
   14979       if (full_args == error_mark_node)
   14980 	return error_mark_node;
   14981 
   14982       /* If this is a default template template argument,
   14983 	 tsubst might not have changed anything.  */
   14984       if (full_args == tmpl_args)
   14985 	return t;
   14986 
   14987       hash = spec_hasher::hash (t, full_args);
   14988       spec = retrieve_specialization (t, full_args, hash);
   14989       if (spec != NULL_TREE)
   14990 	{
   14991 	  if (TYPE_P (spec))
   14992 	    /* Type partial instantiations are stored as the type by
   14993 	       lookup_template_class_1, not here as the template.  */
   14994 	    spec = CLASSTYPE_TI_TEMPLATE (spec);
   14995 	  else if (TREE_CODE (spec) != TEMPLATE_DECL)
   14996 	    spec = DECL_TI_TEMPLATE (spec);
   14997 	  return spec;
   14998 	}
   14999     }
   15000 
   15001   /* Make a new template decl.  It will be similar to the
   15002      original, but will record the current template arguments.
   15003      We also create a new function declaration, which is just
   15004      like the old one, but points to this new template, rather
   15005      than the old one.  */
   15006   r = copy_decl (t);
   15007   gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
   15008   DECL_CHAIN (r) = NULL_TREE;
   15009 
   15010   // Build new template info linking to the original template decl.
   15011   if (!lambda_fntype)
   15012     {
   15013       DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
   15014       SET_DECL_IMPLICIT_INSTANTIATION (r);
   15015     }
   15016   else
   15017     DECL_TEMPLATE_INFO (r) = NULL_TREE;
   15018 
   15019   /* The template parameters for this new template are all the
   15020      template parameters for the old template, except the
   15021      outermost level of parameters.  */
   15022   auto tparm_guard = make_temp_override (current_template_parms);
   15023   DECL_TEMPLATE_PARMS (r)
   15024     = current_template_parms
   15025     = (lambda_tparms
   15026        ? lambda_tparms
   15027        : tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
   15028 				complain));
   15029 
   15030   bool class_p = false;
   15031   tree inner = decl;
   15032   ++processing_template_decl;
   15033   if (TREE_CODE (inner) == FUNCTION_DECL)
   15034     inner = tsubst_function_decl (inner, args, complain, lambda_fntype,
   15035 				  /*use_spec_table=*/false);
   15036   else
   15037     {
   15038       if (TREE_CODE (inner) == TYPE_DECL && !TYPE_DECL_ALIAS_P (inner))
   15039 	{
   15040 	  class_p = true;
   15041 	  inner = TREE_TYPE (inner);
   15042 	}
   15043       if (class_p)
   15044 	inner = tsubst_aggr_type (inner, args, complain,
   15045 				  in_decl, /*entering*/1);
   15046       else
   15047 	inner = tsubst_decl (inner, args, complain, /*use_spec_table=*/false);
   15048     }
   15049   --processing_template_decl;
   15050   if (inner == error_mark_node)
   15051     return error_mark_node;
   15052 
   15053   if (class_p)
   15054     {
   15055       /* For a partial specialization, we need to keep pointing to
   15056 	 the primary template.  */
   15057       if (!DECL_TEMPLATE_SPECIALIZATION (t))
   15058 	{
   15059 	  CLASSTYPE_TI_TEMPLATE (inner) = r;
   15060 	  CLASSTYPE_USE_TEMPLATE (inner) = 0;
   15061 	}
   15062 
   15063       DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (inner);
   15064       inner = TYPE_MAIN_DECL (inner);
   15065     }
   15066   else if (lambda_fntype)
   15067     {
   15068       tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
   15069       DECL_TEMPLATE_INFO (inner) = build_template_info (r, args);
   15070     }
   15071   else
   15072     {
   15073       DECL_TI_TEMPLATE (inner) = r;
   15074       /* Set DECL_TI_ARGS to the full set of template arguments,
   15075 	 which tsubst_function_decl / tsubst_decl didn't do due to
   15076 	 use_spec_table=false.  */
   15077       DECL_TI_ARGS (inner) = full_args;
   15078       DECL_TI_ARGS (r) = DECL_TI_ARGS (inner);
   15079     }
   15080 
   15081   DECL_TEMPLATE_RESULT (r) = inner;
   15082   TREE_TYPE (r) = TREE_TYPE (inner);
   15083   DECL_CONTEXT (r) = DECL_CONTEXT (inner);
   15084 
   15085   if (modules_p ())
   15086     {
   15087       /* Propagate module information from the decl.  */
   15088       DECL_MODULE_EXPORT_P (r) = DECL_MODULE_EXPORT_P (inner);
   15089       if (DECL_LANG_SPECIFIC (inner))
   15090 	/* If this is a constrained template, the above tsubst of
   15091 	   inner can find the unconstrained template, which may have
   15092 	   come from an import.  This is ok, because we don't
   15093 	   register this instantiation (see below).  */
   15094 	gcc_checking_assert (!DECL_MODULE_IMPORT_P (inner)
   15095 			     || (TEMPLATE_PARMS_CONSTRAINTS
   15096 				 (DECL_TEMPLATE_PARMS (t))));
   15097     }
   15098 
   15099   DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
   15100   DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
   15101 
   15102   if (PRIMARY_TEMPLATE_P (t))
   15103     DECL_PRIMARY_TEMPLATE (r) = r;
   15104 
   15105   DECL_UNINSTANTIATED_TEMPLATE_FRIEND_P (r) = false;
   15106 
   15107   if (!lambda_fntype && !class_p)
   15108     {
   15109       /* Record this non-type partial instantiation.  */
   15110       /* FIXME we'd like to always register the TEMPLATE_DECL, or always
   15111 	 the DECL_TEMPLATE_RESULT, but it seems the modules code relies
   15112 	 on this current behavior.  */
   15113       if (TREE_CODE (inner) == FUNCTION_DECL)
   15114 	register_specialization (r, t, full_args, false, hash);
   15115       else
   15116 	register_specialization (inner, t, full_args, false, hash);
   15117     }
   15118 
   15119   return r;
   15120 }
   15121 
   15122 /* True if FN is the op() for a lambda in an uninstantiated template.  */
   15123 
   15124 bool
   15125 lambda_fn_in_template_p (tree fn)
   15126 {
   15127   if (!fn || !LAMBDA_FUNCTION_P (fn))
   15128     return false;
   15129   tree closure = DECL_CONTEXT (fn);
   15130   return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
   15131 }
   15132 
   15133 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
   15134    which the above is true.  */
   15135 
   15136 bool
   15137 regenerated_lambda_fn_p (tree fn)
   15138 {
   15139   if (!fn || !LAMBDA_FUNCTION_P (fn))
   15140     return false;
   15141   tree closure = DECL_CONTEXT (fn);
   15142   tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
   15143   return LAMBDA_EXPR_REGEN_INFO (lam) != NULL_TREE;
   15144 }
   15145 
   15146 /* Return the LAMBDA_EXPR from which T was ultimately regenerated.
   15147    If T is not a regenerated LAMBDA_EXPR, return T.  */
   15148 
   15149 tree
   15150 most_general_lambda (tree t)
   15151 {
   15152   while (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
   15153     t = TI_TEMPLATE (ti);
   15154   return t;
   15155 }
   15156 
   15157 /* Return the set of template arguments used to regenerate the lambda T
   15158    from its most general lambda.  */
   15159 
   15160 tree
   15161 lambda_regenerating_args (tree t)
   15162 {
   15163   if (LAMBDA_FUNCTION_P (t))
   15164     t = CLASSTYPE_LAMBDA_EXPR (DECL_CONTEXT (t));
   15165   gcc_assert (TREE_CODE (t) == LAMBDA_EXPR);
   15166   if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
   15167     return TI_ARGS (ti);
   15168   else
   15169     return NULL_TREE;
   15170 }
   15171 
   15172 /* We're instantiating a variable from template function TCTX.  Return the
   15173    corresponding current enclosing scope.  We can match them up using
   15174    DECL_SOURCE_LOCATION because lambdas only ever have one source location, and
   15175    the DECL_SOURCE_LOCATION for a function instantiation is updated to match
   15176    the template definition in regenerate_decl_from_template.  */
   15177 
   15178 static tree
   15179 enclosing_instantiation_of (tree tctx)
   15180 {
   15181   tree fn = current_function_decl;
   15182 
   15183   /* We shouldn't ever need to do this for other artificial functions.  */
   15184   gcc_assert (!DECL_ARTIFICIAL (tctx) || LAMBDA_FUNCTION_P (tctx));
   15185 
   15186   for (; fn; fn = decl_function_context (fn))
   15187     if (DECL_SOURCE_LOCATION (fn) == DECL_SOURCE_LOCATION (tctx))
   15188       return fn;
   15189   gcc_unreachable ();
   15190 }
   15191 
   15192 /* Substitute the ARGS into the T, which is a _DECL.  Return the
   15193    result of the substitution.  Issue error and warning messages under
   15194    control of COMPLAIN.  The flag USE_SPEC_TABLE controls if we look up
   15195    and insert into the specializations table or if we can assume it's
   15196    the caller's responsibility; this is used by instantiate_template
   15197    to avoid doing some redundant work.  */
   15198 
   15199 static tree
   15200 tsubst_decl (tree t, tree args, tsubst_flags_t complain,
   15201 	     bool use_spec_table /* = true */)
   15202 {
   15203 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
   15204   location_t saved_loc;
   15205   tree r = NULL_TREE;
   15206   tree in_decl = t;
   15207   hashval_t hash = 0;
   15208 
   15209   if (t == error_mark_node)
   15210     return error_mark_node;
   15211 
   15212   /* Set the filename and linenumber to improve error-reporting.  */
   15213   saved_loc = input_location;
   15214   input_location = DECL_SOURCE_LOCATION (t);
   15215 
   15216   switch (TREE_CODE (t))
   15217     {
   15218     case TEMPLATE_DECL:
   15219       r = tsubst_template_decl (t, args, complain,
   15220 				/*lambda_fntype=*/NULL_TREE,
   15221 				/*lambda_tparms=*/NULL_TREE);
   15222       break;
   15223 
   15224     case FUNCTION_DECL:
   15225       r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE,
   15226 				use_spec_table);
   15227       break;
   15228 
   15229     case PARM_DECL:
   15230       {
   15231 	tree type = NULL_TREE;
   15232         int i, len = 1;
   15233         tree expanded_types = NULL_TREE;
   15234         tree prev_r = NULL_TREE;
   15235         tree first_r = NULL_TREE;
   15236 
   15237         if (DECL_PACK_P (t))
   15238           {
   15239             /* If there is a local specialization that isn't a
   15240                parameter pack, it means that we're doing a "simple"
   15241                substitution from inside tsubst_pack_expansion. Just
   15242                return the local specialization (which will be a single
   15243                parm).  */
   15244             tree spec = retrieve_local_specialization (t);
   15245             if (spec
   15246                 && TREE_CODE (spec) == PARM_DECL
   15247                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
   15248               RETURN (spec);
   15249 
   15250             /* Expand the TYPE_PACK_EXPANSION that provides the types for
   15251                the parameters in this function parameter pack.  */
   15252             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
   15253 						    complain, in_decl);
   15254             if (TREE_CODE (expanded_types) == TREE_VEC)
   15255               {
   15256                 len = TREE_VEC_LENGTH (expanded_types);
   15257 
   15258                 /* Zero-length parameter packs are boring. Just substitute
   15259                    into the chain.  */
   15260 		if (len == 0 && !cp_unevaluated_operand)
   15261                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
   15262 				  TREE_CHAIN (t)));
   15263               }
   15264             else
   15265               {
   15266                 /* All we did was update the type. Make a note of that.  */
   15267                 type = expanded_types;
   15268                 expanded_types = NULL_TREE;
   15269               }
   15270           }
   15271 
   15272         /* Loop through all of the parameters we'll build. When T is
   15273            a function parameter pack, LEN is the number of expanded
   15274            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
   15275         r = NULL_TREE;
   15276         for (i = 0; i < len; ++i)
   15277           {
   15278             prev_r = r;
   15279             r = copy_node (t);
   15280             if (DECL_TEMPLATE_PARM_P (t))
   15281               SET_DECL_TEMPLATE_PARM_P (r);
   15282 
   15283             if (expanded_types)
   15284               /* We're on the Ith parameter of the function parameter
   15285                  pack.  */
   15286               {
   15287                 /* Get the Ith type.  */
   15288                 type = TREE_VEC_ELT (expanded_types, i);
   15289 
   15290 		/* Rename the parameter to include the index.  */
   15291 		DECL_NAME (r)
   15292 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
   15293               }
   15294             else if (!type)
   15295               /* We're dealing with a normal parameter.  */
   15296               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   15297 
   15298             type = type_decays_to (type);
   15299             TREE_TYPE (r) = type;
   15300             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
   15301 
   15302             if (DECL_INITIAL (r))
   15303               {
   15304                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
   15305                   DECL_INITIAL (r) = TREE_TYPE (r);
   15306                 else
   15307                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
   15308                                              complain, in_decl);
   15309               }
   15310 
   15311             DECL_CONTEXT (r) = NULL_TREE;
   15312 
   15313             if (!DECL_TEMPLATE_PARM_P (r))
   15314               DECL_ARG_TYPE (r) = type_passed_as (type);
   15315 
   15316 	    if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
   15317 						 args, complain, in_decl))
   15318 	      return error_mark_node;
   15319 
   15320             /* Keep track of the first new parameter we
   15321                generate. That's what will be returned to the
   15322                caller.  */
   15323             if (!first_r)
   15324               first_r = r;
   15325 
   15326             /* Build a proper chain of parameters when substituting
   15327                into a function parameter pack.  */
   15328             if (prev_r)
   15329               DECL_CHAIN (prev_r) = r;
   15330           }
   15331 
   15332 	/* If cp_unevaluated_operand is set, we're just looking for a
   15333 	   single dummy parameter, so don't keep going.  */
   15334 	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
   15335 	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
   15336 				   complain, DECL_CHAIN (t));
   15337 
   15338         /* FIRST_R contains the start of the chain we've built.  */
   15339         r = first_r;
   15340       }
   15341       break;
   15342 
   15343     case FIELD_DECL:
   15344       {
   15345 	tree type = NULL_TREE;
   15346 	tree vec = NULL_TREE;
   15347 	tree expanded_types = NULL_TREE;
   15348 	int len = 1;
   15349 
   15350 	if (PACK_EXPANSION_P (TREE_TYPE (t)))
   15351 	  {
   15352 	    /* This field is a lambda capture pack.  Return a TREE_VEC of
   15353 	       the expanded fields to instantiate_class_template_1.  */
   15354             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
   15355 						    complain, in_decl);
   15356             if (TREE_CODE (expanded_types) == TREE_VEC)
   15357               {
   15358                 len = TREE_VEC_LENGTH (expanded_types);
   15359 		vec = make_tree_vec (len);
   15360               }
   15361             else
   15362               {
   15363                 /* All we did was update the type. Make a note of that.  */
   15364                 type = expanded_types;
   15365                 expanded_types = NULL_TREE;
   15366               }
   15367 	  }
   15368 
   15369 	for (int i = 0; i < len; ++i)
   15370 	  {
   15371 	    r = copy_decl (t);
   15372 	    if (expanded_types)
   15373 	      {
   15374 		type = TREE_VEC_ELT (expanded_types, i);
   15375 		DECL_NAME (r)
   15376 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
   15377 	      }
   15378             else if (!type)
   15379               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   15380 
   15381 	    if (type == error_mark_node)
   15382 	      RETURN (error_mark_node);
   15383 	    TREE_TYPE (r) = type;
   15384 	    cp_apply_type_quals_to_decl (cp_type_quals (type), r);
   15385 
   15386 	    if (DECL_C_BIT_FIELD (r))
   15387 	      /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
   15388 		 number of bits.  */
   15389 	      DECL_BIT_FIELD_REPRESENTATIVE (r)
   15390 		= tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
   15391 			       complain, in_decl);
   15392 	    if (DECL_INITIAL (t))
   15393 	      {
   15394 		/* Set up DECL_TEMPLATE_INFO so that we can get at the
   15395 		   NSDMI in perform_member_init.  Still set DECL_INITIAL
   15396 		   so that we know there is one.  */
   15397 		DECL_INITIAL (r) = void_node;
   15398 		gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
   15399 		retrofit_lang_decl (r);
   15400 		DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
   15401 	      }
   15402 	    /* We don't have to set DECL_CONTEXT here; it is set by
   15403 	       finish_member_declaration.  */
   15404 	    DECL_CHAIN (r) = NULL_TREE;
   15405 
   15406 	    if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
   15407 						 args, complain, in_decl))
   15408 	      return error_mark_node;
   15409 
   15410 	    if (vec)
   15411 	      TREE_VEC_ELT (vec, i) = r;
   15412 	  }
   15413 
   15414 	if (vec)
   15415 	  r = vec;
   15416       }
   15417       break;
   15418 
   15419     case USING_DECL:
   15420       /* We reach here only for member using decls.  We also need to check
   15421 	 uses_template_parms because DECL_DEPENDENT_P is not set for a
   15422 	 using-declaration that designates a member of the current
   15423 	 instantiation (c++/53549).  */
   15424       if (DECL_DEPENDENT_P (t)
   15425 	  || uses_template_parms (USING_DECL_SCOPE (t)))
   15426 	{
   15427 	  /* True iff this using-decl was written as a pack expansion
   15428 	     (and a pack appeared in its scope or name).  If a pack
   15429 	     appeared in both, we expand the packs separately and
   15430 	     manually merge them.  */
   15431 	  bool variadic_p = false;
   15432 
   15433 	  tree scope = USING_DECL_SCOPE (t);
   15434 	  if (PACK_EXPANSION_P (scope))
   15435 	    {
   15436 	      scope = tsubst_pack_expansion (scope, args,
   15437 					     complain | tf_qualifying_scope,
   15438 					     in_decl);
   15439 	      variadic_p = true;
   15440 	    }
   15441 	  else
   15442 	    scope = tsubst_scope (scope, args, complain, in_decl);
   15443 
   15444 	  tree name = DECL_NAME (t);
   15445 	  if (IDENTIFIER_CONV_OP_P (name)
   15446 	      && PACK_EXPANSION_P (TREE_TYPE (name)))
   15447 	    {
   15448 	      name = tsubst_pack_expansion (TREE_TYPE (name), args,
   15449 					    complain, in_decl);
   15450 	      if (name == error_mark_node)
   15451 		{
   15452 		  r = error_mark_node;
   15453 		  break;
   15454 		}
   15455 	      for (tree& elt : tree_vec_range (name))
   15456 		elt = make_conv_op_name (elt);
   15457 	      variadic_p = true;
   15458 	    }
   15459 	  else
   15460 	    name = tsubst_name (name, args, complain, in_decl);
   15461 
   15462 	  int len;
   15463 	  if (!variadic_p)
   15464 	    len = 1;
   15465 	  else if (TREE_CODE (scope) == TREE_VEC
   15466 		   && TREE_CODE (name) == TREE_VEC)
   15467 	    {
   15468 	      if (TREE_VEC_LENGTH (scope) != TREE_VEC_LENGTH (name))
   15469 		{
   15470 		  error ("mismatched argument pack lengths (%d vs %d)",
   15471 			 TREE_VEC_LENGTH (scope), TREE_VEC_LENGTH (name));
   15472 		  r = error_mark_node;
   15473 		  break;
   15474 		}
   15475 	      len = TREE_VEC_LENGTH (scope);
   15476 	    }
   15477 	  else if (TREE_CODE (scope) == TREE_VEC)
   15478 	    len = TREE_VEC_LENGTH (scope);
   15479 	  else /* TREE_CODE (name) == TREE_VEC  */
   15480 	    len = TREE_VEC_LENGTH (name);
   15481 
   15482 	  r = make_tree_vec (len);
   15483 	  for (int i = 0; i < len; ++i)
   15484 	    {
   15485 	      tree escope = (TREE_CODE (scope) == TREE_VEC
   15486 			     ? TREE_VEC_ELT (scope, i)
   15487 			     : scope);
   15488 	      tree ename = (TREE_CODE (name) == TREE_VEC
   15489 			    ? TREE_VEC_ELT (name, i)
   15490 			    : name);
   15491 	      tree elt = do_class_using_decl (escope, ename);
   15492 	      if (!elt)
   15493 		{
   15494 		  r = error_mark_node;
   15495 		  break;
   15496 		}
   15497 	      TREE_PROTECTED (elt) = TREE_PROTECTED (t);
   15498 	      TREE_PRIVATE (elt) = TREE_PRIVATE (t);
   15499 	      TREE_VEC_ELT (r, i) = elt;
   15500 	    }
   15501 
   15502 	  if (!variadic_p && r != error_mark_node)
   15503 	    r = TREE_VEC_ELT (r, 0);
   15504 	}
   15505       else
   15506 	{
   15507 	  r = copy_node (t);
   15508 	  DECL_CHAIN (r) = NULL_TREE;
   15509 	}
   15510       break;
   15511 
   15512     case TYPE_DECL:
   15513     case VAR_DECL:
   15514       {
   15515 	tree argvec = NULL_TREE;
   15516 	tree gen_tmpl = NULL_TREE;
   15517 	tree tmpl = NULL_TREE;
   15518 	tree type = NULL_TREE;
   15519 
   15520 	if (TREE_TYPE (t) == error_mark_node)
   15521 	  RETURN (error_mark_node);
   15522 
   15523 	if (TREE_CODE (t) == TYPE_DECL
   15524 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
   15525 	  {
   15526 	    /* If this is the canonical decl, we don't have to
   15527 	       mess with instantiations, and often we can't (for
   15528 	       typename, template type parms and such).  Note that
   15529 	       TYPE_NAME is not correct for the above test if
   15530 	       we've copied the type for a typedef.  */
   15531 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   15532 	    if (type == error_mark_node)
   15533 	      RETURN (error_mark_node);
   15534 	    r = TYPE_NAME (type);
   15535 	    break;
   15536 	  }
   15537 
   15538 	/* Check to see if we already have the specialization we
   15539 	   need.  */
   15540 	tree spec = NULL_TREE;
   15541 	bool local_p = false;
   15542 	tree ctx = DECL_CONTEXT (t);
   15543 	if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t))
   15544 	    && (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t)))
   15545 	  {
   15546 	    local_p = false;
   15547 	    if (DECL_CLASS_SCOPE_P (t))
   15548 	      {
   15549 		ctx = tsubst_aggr_type (ctx, args,
   15550 					complain,
   15551 					in_decl, /*entering_scope=*/1);
   15552 		if (DECL_SELF_REFERENCE_P (t))
   15553 		  /* The context and type of an injected-class-name are
   15554 		     the same, so we don't need to substitute both.  */
   15555 		  type = ctx;
   15556 		/* If CTX is unchanged, then T is in fact the
   15557 		   specialization we want.  That situation occurs when
   15558 		   referencing a static data member within in its own
   15559 		   class.  We can use pointer equality, rather than
   15560 		   same_type_p, because DECL_CONTEXT is always
   15561 		   canonical...  */
   15562 		if (ctx == DECL_CONTEXT (t)
   15563 		    /* ... unless T is a member template; in which
   15564 		       case our caller can be willing to create a
   15565 		       specialization of that template represented
   15566 		       by T.  */
   15567 		    && !(DECL_TI_TEMPLATE (t)
   15568 			 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
   15569 		  spec = t;
   15570 	      }
   15571 
   15572 	    if (!spec)
   15573 	      {
   15574 		tmpl = DECL_TI_TEMPLATE (t);
   15575 		if (use_spec_table)
   15576 		  {
   15577 		    argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
   15578 		    if (argvec == error_mark_node)
   15579 		      RETURN (error_mark_node);
   15580 		    gen_tmpl = most_general_template (tmpl);
   15581 		    hash = spec_hasher::hash (gen_tmpl, argvec);
   15582 		    spec = retrieve_specialization (gen_tmpl, argvec, hash);
   15583 		  }
   15584 		else
   15585 		  argvec = args;
   15586 	      }
   15587 	  }
   15588 	else
   15589 	  {
   15590 	    if (!(VAR_P (t) && DECL_LOCAL_DECL_P (t)))
   15591 	      /* Subsequent calls to pushdecl will fill this in.  */
   15592 	      ctx = NULL_TREE;
   15593 	    /* A local variable.  */
   15594 	    local_p = true;
   15595 	    /* Unless this is a reference to a static variable from an
   15596 	       enclosing function, in which case we need to fill it in now.  */
   15597 	    if (TREE_STATIC (t))
   15598 	      {
   15599 		tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
   15600 		if (fn != current_function_decl)
   15601 		  ctx = fn;
   15602 	      }
   15603 	    spec = retrieve_local_specialization (t);
   15604 	  }
   15605 	/* If we already have the specialization we need, there is
   15606 	   nothing more to do.  */
   15607 	if (spec)
   15608 	  {
   15609 	    r = spec;
   15610 	    break;
   15611 	  }
   15612 
   15613 	/* Create a new node for the specialization we need.  */
   15614 	if (type == NULL_TREE)
   15615 	  {
   15616 	    if (is_typedef_decl (t))
   15617 	      type = DECL_ORIGINAL_TYPE (t);
   15618 	    else
   15619 	      type = TREE_TYPE (t);
   15620 	    if (VAR_P (t)
   15621 		&& VAR_HAD_UNKNOWN_BOUND (t)
   15622 		&& type != error_mark_node)
   15623 	      type = strip_array_domain (type);
   15624 	    tsubst_flags_t tcomplain = complain;
   15625 	    if (VAR_P (t))
   15626 	      tcomplain |= tf_tst_ok;
   15627 	    type = tsubst (type, args, tcomplain, in_decl);
   15628 	    /* Substituting the type might have recursively instantiated this
   15629 	       same alias (c++/86171).  */
   15630 	    if (use_spec_table && gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
   15631 		&& (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
   15632 	      {
   15633 		r = spec;
   15634 		break;
   15635 	      }
   15636 	  }
   15637 	if (type == error_mark_node && !(complain & tf_error))
   15638 	  RETURN (error_mark_node);
   15639 	r = copy_decl (t);
   15640 	if (VAR_P (r))
   15641 	  {
   15642 	    DECL_INITIALIZED_P (r) = 0;
   15643 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
   15644 	    if (TREE_CODE (type) == FUNCTION_TYPE)
   15645 	      {
   15646 		/* It may seem that this case cannot occur, since:
   15647 
   15648 		   typedef void f();
   15649 		   void g() { f x; }
   15650 
   15651 		   declares a function, not a variable.  However:
   15652 
   15653 		   typedef void f();
   15654 		   template <typename T> void g() { T t; }
   15655 		   template void g<f>();
   15656 
   15657 		   is an attempt to declare a variable with function
   15658 		   type.  */
   15659 		error ("variable %qD has function type",
   15660 		       /* R is not yet sufficiently initialized, so we
   15661 			  just use its name.  */
   15662 		       DECL_NAME (r));
   15663 		RETURN (error_mark_node);
   15664 	      }
   15665 	    type = complete_type (type);
   15666 	    /* Wait until cp_finish_decl to set this again, to handle
   15667 	       circular dependency (template/instantiate6.C). */
   15668 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
   15669 	    type = check_var_type (DECL_NAME (r), type,
   15670 				   DECL_SOURCE_LOCATION (r));
   15671 	    if (DECL_HAS_VALUE_EXPR_P (t))
   15672 	      {
   15673 		tree ve = DECL_VALUE_EXPR (t);
   15674 		/* If the DECL_VALUE_EXPR is converted to the declared type,
   15675 		   preserve the identity so that gimplify_type_sizes works.  */
   15676 		bool nop = (TREE_CODE (ve) == NOP_EXPR);
   15677 		if (nop)
   15678 		  ve = TREE_OPERAND (ve, 0);
   15679 		ve = tsubst_expr (ve, args, complain, in_decl);
   15680 		if (REFERENCE_REF_P (ve))
   15681 		  {
   15682 		    gcc_assert (TYPE_REF_P (type));
   15683 		    ve = TREE_OPERAND (ve, 0);
   15684 		  }
   15685 		if (nop)
   15686 		  ve = build_nop (type, ve);
   15687 		else if (DECL_LANG_SPECIFIC (t)
   15688 			 && DECL_OMP_PRIVATIZED_MEMBER (t)
   15689 			 && TREE_CODE (ve) == COMPONENT_REF
   15690 			 && TREE_CODE (TREE_OPERAND (ve, 1)) == FIELD_DECL
   15691 			 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (ve, 1)) == type)
   15692 		  type = TREE_TYPE (ve);
   15693 		else
   15694 		  gcc_checking_assert (TYPE_MAIN_VARIANT (TREE_TYPE (ve))
   15695 				       == TYPE_MAIN_VARIANT (type));
   15696 		SET_DECL_VALUE_EXPR (r, ve);
   15697 	      }
   15698 	    if (CP_DECL_THREAD_LOCAL_P (r)
   15699 		&& !processing_template_decl)
   15700 	      set_decl_tls_model (r, decl_default_tls_model (r));
   15701 	  }
   15702 	else if (DECL_SELF_REFERENCE_P (t))
   15703 	  SET_DECL_SELF_REFERENCE_P (r);
   15704 	TREE_TYPE (r) = type;
   15705 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
   15706 	DECL_CONTEXT (r) = ctx;
   15707 	/* Clear out the mangled name and RTL for the instantiation.  */
   15708 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
   15709 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
   15710 	  SET_DECL_RTL (r, NULL);
   15711 	set_instantiating_module (r);
   15712 
   15713 	/* The initializer must not be expanded until it is required;
   15714 	   see [temp.inst].  */
   15715 	DECL_INITIAL (r) = NULL_TREE;
   15716 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
   15717 	if (VAR_P (r))
   15718 	  {
   15719 	    if (DECL_LANG_SPECIFIC (r))
   15720 	      SET_DECL_DEPENDENT_INIT_P (r, false);
   15721 
   15722 	    SET_DECL_MODE (r, VOIDmode);
   15723 
   15724 	    /* Possibly limit visibility based on template args.  */
   15725 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
   15726 	    if (DECL_VISIBILITY_SPECIFIED (t))
   15727 	      {
   15728 		DECL_VISIBILITY_SPECIFIED (r) = 0;
   15729 		DECL_ATTRIBUTES (r)
   15730 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
   15731 	      }
   15732 	    determine_visibility (r);
   15733 	    if ((!local_p || TREE_STATIC (t)) && DECL_SECTION_NAME (t))
   15734 	      set_decl_section_name (r, t);
   15735 	  }
   15736 
   15737 	if (!local_p)
   15738 	  {
   15739 	    /* A static data member declaration is always marked
   15740 	       external when it is declared in-class, even if an
   15741 	       initializer is present.  We mimic the non-template
   15742 	       processing here.  */
   15743 	    DECL_EXTERNAL (r) = 1;
   15744 	    if (DECL_NAMESPACE_SCOPE_P (t))
   15745 	      DECL_NOT_REALLY_EXTERN (r) = 1;
   15746 
   15747 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
   15748 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
   15749 	    if (use_spec_table)
   15750 	      register_specialization (r, gen_tmpl, argvec, false, hash);
   15751 	  }
   15752 	else
   15753 	  {
   15754 	    if (DECL_LANG_SPECIFIC (r))
   15755 	      DECL_TEMPLATE_INFO (r) = NULL_TREE;
   15756 	    if (!cp_unevaluated_operand)
   15757 	      register_local_specialization (r, t);
   15758 	  }
   15759 
   15760 	DECL_CHAIN (r) = NULL_TREE;
   15761 
   15762 	if (!apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
   15763 					     /*flags=*/0,
   15764 					     args, complain, in_decl))
   15765 	  return error_mark_node;
   15766 
   15767 	/* Preserve a typedef that names a type.  */
   15768 	if (is_typedef_decl (r) && type != error_mark_node)
   15769 	  {
   15770 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
   15771 	    set_underlying_type (r);
   15772 
   15773 	    /* common_handle_aligned_attribute doesn't apply the alignment
   15774 	       to DECL_ORIGINAL_TYPE.  */
   15775 	    if (TYPE_USER_ALIGN (TREE_TYPE (t)))
   15776 	      TREE_TYPE (r) = build_aligned_type (TREE_TYPE (r),
   15777 						  TYPE_ALIGN (TREE_TYPE (t)));
   15778 	  }
   15779 
   15780 	layout_decl (r, 0);
   15781       }
   15782       break;
   15783 
   15784     default:
   15785       gcc_unreachable ();
   15786     }
   15787 #undef RETURN
   15788 
   15789  out:
   15790   /* Restore the file and line information.  */
   15791   input_location = saved_loc;
   15792 
   15793   return r;
   15794 }
   15795 
   15796 /* Substitute into the complete parameter type list PARMS.  */
   15797 
   15798 tree
   15799 tsubst_function_parms (tree parms,
   15800 		       tree args,
   15801 		       tsubst_flags_t complain,
   15802 		       tree in_decl)
   15803 {
   15804   return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
   15805 }
   15806 
   15807 /* Substitute into the ARG_TYPES of a function type.
   15808    If END is a TREE_CHAIN, leave it and any following types
   15809    un-substituted.  */
   15810 
   15811 static tree
   15812 tsubst_arg_types (tree arg_types,
   15813 		  tree args,
   15814 		  tree end,
   15815 		  tsubst_flags_t complain,
   15816 		  tree in_decl)
   15817 {
   15818   tree type = NULL_TREE;
   15819   int len = 1;
   15820   tree expanded_args = NULL_TREE;
   15821 
   15822   if (!arg_types || arg_types == void_list_node || arg_types == end)
   15823     return arg_types;
   15824 
   15825   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
   15826     {
   15827       /* For a pack expansion, perform substitution on the
   15828          entire expression. Later on, we'll handle the arguments
   15829          one-by-one.  */
   15830       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
   15831                                             args, complain, in_decl);
   15832 
   15833       if (TREE_CODE (expanded_args) == TREE_VEC)
   15834         /* So that we'll spin through the parameters, one by one.  */
   15835 	len = TREE_VEC_LENGTH (expanded_args);
   15836       else
   15837         {
   15838           /* We only partially substituted into the parameter
   15839              pack. Our type is TYPE_PACK_EXPANSION.  */
   15840           type = expanded_args;
   15841           expanded_args = NULL_TREE;
   15842         }
   15843     }
   15844   else
   15845     type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
   15846 
   15847   /* Check if a substituted type is erroneous before substituting into
   15848      the rest of the chain.  */
   15849   for (int i = 0; i < len; i++)
   15850     {
   15851       if (expanded_args)
   15852 	type = TREE_VEC_ELT (expanded_args, i);
   15853 
   15854       if (type == error_mark_node)
   15855 	return error_mark_node;
   15856       if (VOID_TYPE_P (type))
   15857 	{
   15858 	  if (complain & tf_error)
   15859 	    {
   15860 	      error ("invalid parameter type %qT", type);
   15861 	      if (in_decl)
   15862 		error ("in declaration %q+D", in_decl);
   15863 	    }
   15864 	  return error_mark_node;
   15865 	}
   15866     }
   15867 
   15868   /* We do not substitute into default arguments here.  The standard
   15869      mandates that they be instantiated only when needed, which is
   15870      done in build_over_call.  */
   15871   tree default_arg = TREE_PURPOSE (arg_types);
   15872 
   15873   /* Except that we do substitute default arguments under tsubst_lambda_expr,
   15874      since the new op() won't have any associated template arguments for us
   15875      to refer to later.  */
   15876   if (lambda_fn_in_template_p (in_decl)
   15877       || (in_decl && TREE_CODE (in_decl) == FUNCTION_DECL
   15878 	  && DECL_LOCAL_DECL_P (in_decl)))
   15879     default_arg = tsubst_expr (default_arg, args, complain, in_decl);
   15880 
   15881   tree remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
   15882 					       args, end, complain, in_decl);
   15883   if (remaining_arg_types == error_mark_node)
   15884     return error_mark_node;
   15885 
   15886   for (int i = len-1; i >= 0; i--)
   15887     {
   15888       if (expanded_args)
   15889 	type = TREE_VEC_ELT (expanded_args, i);
   15890 
   15891       /* Do array-to-pointer, function-to-pointer conversion, and ignore
   15892 	 top-level qualifiers as required.  */
   15893       type = cv_unqualified (type_decays_to (type));
   15894 
   15895       if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
   15896 	{
   15897 	  /* We've instantiated a template before its default arguments
   15898 	     have been parsed.  This can happen for a nested template
   15899 	     class, and is not an error unless we require the default
   15900 	     argument in a call of this function.  */
   15901 	  remaining_arg_types
   15902 	    = tree_cons (default_arg, type, remaining_arg_types);
   15903 	  vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
   15904 			 remaining_arg_types);
   15905 	}
   15906       else
   15907 	remaining_arg_types
   15908 	  = hash_tree_cons (default_arg, type, remaining_arg_types);
   15909     }
   15910 
   15911   return remaining_arg_types;
   15912 }
   15913 
   15914 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
   15915    *not* handle the exception-specification for FNTYPE, because the
   15916    initial substitution of explicitly provided template parameters
   15917    during argument deduction forbids substitution into the
   15918    exception-specification:
   15919 
   15920      [temp.deduct]
   15921 
   15922      All references in the function type of the function template to  the
   15923      corresponding template parameters are replaced by the specified tem-
   15924      plate argument values.  If a substitution in a template parameter or
   15925      in  the function type of the function template results in an invalid
   15926      type, type deduction fails.  [Note: The equivalent  substitution  in
   15927      exception specifications is done only when the function is instanti-
   15928      ated, at which point a program is  ill-formed  if  the  substitution
   15929      results in an invalid type.]  */
   15930 
   15931 static tree
   15932 tsubst_function_type (tree t,
   15933 		      tree args,
   15934 		      tsubst_flags_t complain,
   15935 		      tree in_decl)
   15936 {
   15937   tree return_type;
   15938   tree arg_types = NULL_TREE;
   15939 
   15940   /* The TYPE_CONTEXT is not used for function/method types.  */
   15941   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
   15942 
   15943   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
   15944      failure.  */
   15945   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
   15946 
   15947   if (late_return_type_p)
   15948     {
   15949       /* Substitute the argument types.  */
   15950       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
   15951 				    complain, in_decl);
   15952       if (arg_types == error_mark_node)
   15953 	return error_mark_node;
   15954 
   15955       tree save_ccp = current_class_ptr;
   15956       tree save_ccr = current_class_ref;
   15957       tree this_type = (TREE_CODE (t) == METHOD_TYPE
   15958 			? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
   15959       bool do_inject = this_type && CLASS_TYPE_P (this_type);
   15960       if (do_inject)
   15961 	{
   15962 	  /* DR 1207: 'this' is in scope in the trailing return type.  */
   15963 	  inject_this_parameter (this_type, cp_type_quals (this_type));
   15964 	}
   15965 
   15966       /* Substitute the return type.  */
   15967       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   15968 
   15969       if (do_inject)
   15970 	{
   15971 	  current_class_ptr = save_ccp;
   15972 	  current_class_ref = save_ccr;
   15973 	}
   15974     }
   15975   else
   15976     /* Substitute the return type.  */
   15977     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   15978 
   15979   if (return_type == error_mark_node)
   15980     return error_mark_node;
   15981   /* DR 486 clarifies that creation of a function type with an
   15982      invalid return type is a deduction failure.  */
   15983   if (TREE_CODE (return_type) == ARRAY_TYPE
   15984       || TREE_CODE (return_type) == FUNCTION_TYPE)
   15985     {
   15986       if (complain & tf_error)
   15987 	{
   15988 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
   15989 	    error ("function returning an array");
   15990 	  else
   15991 	    error ("function returning a function");
   15992 	}
   15993       return error_mark_node;
   15994     }
   15995 
   15996   if (!late_return_type_p)
   15997     {
   15998       /* Substitute the argument types.  */
   15999       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
   16000 				    complain, in_decl);
   16001       if (arg_types == error_mark_node)
   16002 	return error_mark_node;
   16003     }
   16004 
   16005   /* Construct a new type node and return it.  */
   16006   return rebuild_function_or_method_type (t, return_type, arg_types,
   16007 					  /*raises=*/NULL_TREE, complain);
   16008 }
   16009 
   16010 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
   16011    ARGS into that specification, and return the substituted
   16012    specification.  If there is no specification, return NULL_TREE.  */
   16013 
   16014 static tree
   16015 tsubst_exception_specification (tree fntype,
   16016 				tree args,
   16017 				tsubst_flags_t complain,
   16018 				tree in_decl,
   16019 				bool defer_ok)
   16020 {
   16021   tree specs;
   16022   tree new_specs;
   16023 
   16024   specs = TYPE_RAISES_EXCEPTIONS (fntype);
   16025   new_specs = NULL_TREE;
   16026   if (specs && TREE_PURPOSE (specs))
   16027     {
   16028       /* A noexcept-specifier.  */
   16029       tree expr = TREE_PURPOSE (specs);
   16030       if (TREE_CODE (expr) == INTEGER_CST)
   16031 	new_specs = expr;
   16032       else if (defer_ok)
   16033 	{
   16034 	  /* Defer instantiation of noexcept-specifiers to avoid
   16035 	     excessive instantiations (c++/49107).  */
   16036 	  new_specs = make_node (DEFERRED_NOEXCEPT);
   16037 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
   16038 	    {
   16039 	      /* We already partially instantiated this member template,
   16040 		 so combine the new args with the old.  */
   16041 	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
   16042 		= DEFERRED_NOEXCEPT_PATTERN (expr);
   16043 	      DEFERRED_NOEXCEPT_ARGS (new_specs)
   16044 		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
   16045 	    }
   16046 	  else
   16047 	    {
   16048 	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
   16049 	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
   16050 	    }
   16051 	}
   16052       else
   16053 	{
   16054 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
   16055 	    {
   16056 	      args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
   16057 					   args);
   16058 	      expr = DEFERRED_NOEXCEPT_PATTERN (expr);
   16059 	    }
   16060 	  new_specs = tsubst_expr (expr, args, complain, in_decl);
   16061 	}
   16062       new_specs = build_noexcept_spec (new_specs, complain);
   16063       /* We've instantiated a template before a noexcept-specifier
   16064 	 contained therein has been parsed.  This can happen for
   16065 	 a nested template class:
   16066 
   16067 	  struct S {
   16068 	    template<typename> struct B { B() noexcept(...); };
   16069 	    struct A : B<int> { ... use B() ... };
   16070 	  };
   16071 
   16072 	 where completing B<int> will trigger instantiating the
   16073 	 noexcept, even though we only parse it at the end of S.  */
   16074       if (UNPARSED_NOEXCEPT_SPEC_P (specs))
   16075 	{
   16076 	  gcc_checking_assert (defer_ok);
   16077 	  vec_safe_push (DEFPARSE_INSTANTIATIONS (expr), new_specs);
   16078 	}
   16079     }
   16080   else if (specs)
   16081     {
   16082       if (! TREE_VALUE (specs))
   16083 	new_specs = specs;
   16084       else
   16085 	while (specs)
   16086 	  {
   16087 	    tree spec;
   16088             int i, len = 1;
   16089             tree expanded_specs = NULL_TREE;
   16090 
   16091             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
   16092               {
   16093                 /* Expand the pack expansion type.  */
   16094                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
   16095                                                        args, complain,
   16096                                                        in_decl);
   16097 
   16098 		if (expanded_specs == error_mark_node)
   16099 		  return error_mark_node;
   16100 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
   16101 		  len = TREE_VEC_LENGTH (expanded_specs);
   16102 		else
   16103 		  {
   16104 		    /* We're substituting into a member template, so
   16105 		       we got a TYPE_PACK_EXPANSION back.  Add that
   16106 		       expansion and move on.  */
   16107 		    gcc_assert (TREE_CODE (expanded_specs)
   16108 				== TYPE_PACK_EXPANSION);
   16109 		    new_specs = add_exception_specifier (new_specs,
   16110 							 expanded_specs,
   16111 							 complain);
   16112 		    specs = TREE_CHAIN (specs);
   16113 		    continue;
   16114 		  }
   16115               }
   16116 
   16117             for (i = 0; i < len; ++i)
   16118               {
   16119                 if (expanded_specs)
   16120                   spec = TREE_VEC_ELT (expanded_specs, i);
   16121                 else
   16122                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
   16123                 if (spec == error_mark_node)
   16124                   return spec;
   16125                 new_specs = add_exception_specifier (new_specs, spec,
   16126                                                      complain);
   16127               }
   16128 
   16129             specs = TREE_CHAIN (specs);
   16130 	  }
   16131     }
   16132   return new_specs;
   16133 }
   16134 
   16135 /* Substitute through a TREE_LIST of types or expressions, handling pack
   16136    expansions.  */
   16137 
   16138 tree
   16139 tsubst_tree_list (tree t, tree args, tsubst_flags_t complain, tree in_decl)
   16140 {
   16141   if (t == void_list_node)
   16142     return t;
   16143 
   16144   tree purpose = TREE_PURPOSE (t);
   16145   tree purposevec = NULL_TREE;
   16146   if (!purpose)
   16147     ;
   16148   else if (PACK_EXPANSION_P (purpose))
   16149     {
   16150       purpose = tsubst_pack_expansion (purpose, args, complain, in_decl);
   16151       if (TREE_CODE (purpose) == TREE_VEC)
   16152 	purposevec = purpose;
   16153     }
   16154   else if (TYPE_P (purpose))
   16155     purpose = tsubst (purpose, args, complain, in_decl);
   16156   else
   16157     purpose = tsubst_expr (purpose, args, complain, in_decl);
   16158   if (purpose == error_mark_node || purposevec == error_mark_node)
   16159     return error_mark_node;
   16160 
   16161   tree value = TREE_VALUE (t);
   16162   tree valuevec = NULL_TREE;
   16163   if (!value)
   16164     ;
   16165   else if (PACK_EXPANSION_P (value))
   16166     {
   16167       value = tsubst_pack_expansion (value, args, complain, in_decl);
   16168       if (TREE_CODE (value) == TREE_VEC)
   16169 	valuevec = value;
   16170     }
   16171   else if (TYPE_P (value))
   16172     value = tsubst (value, args, complain, in_decl);
   16173   else
   16174     value = tsubst_expr (value, args, complain, in_decl);
   16175   if (value == error_mark_node || valuevec == error_mark_node)
   16176     return error_mark_node;
   16177 
   16178   tree chain = TREE_CHAIN (t);
   16179   if (!chain)
   16180     ;
   16181   else if (TREE_CODE (chain) == TREE_LIST)
   16182     chain = tsubst_tree_list (chain, args, complain, in_decl);
   16183   else if (TYPE_P (chain))
   16184     chain = tsubst (chain, args, complain, in_decl);
   16185   else
   16186     chain = tsubst_expr (chain, args, complain, in_decl);
   16187   if (chain == error_mark_node)
   16188     return error_mark_node;
   16189 
   16190   if (purpose == TREE_PURPOSE (t)
   16191       && value == TREE_VALUE (t)
   16192       && chain == TREE_CHAIN (t))
   16193     return t;
   16194 
   16195   int len;
   16196   /* Determine the number of arguments.  */
   16197   if (purposevec)
   16198     {
   16199       len = TREE_VEC_LENGTH (purposevec);
   16200       gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
   16201     }
   16202   else if (valuevec)
   16203     len = TREE_VEC_LENGTH (valuevec);
   16204   else
   16205     len = 1;
   16206 
   16207   for (int i = len; i-- > 0; )
   16208     {
   16209       if (purposevec)
   16210 	purpose = TREE_VEC_ELT (purposevec, i);
   16211       if (valuevec)
   16212 	value = TREE_VEC_ELT (valuevec, i);
   16213 
   16214       if (value && TYPE_P (value))
   16215 	chain = hash_tree_cons (purpose, value, chain);
   16216       else
   16217 	chain = tree_cons (purpose, value, chain);
   16218     }
   16219 
   16220   return chain;
   16221 }
   16222 
   16223 /* Take the tree structure T and replace template parameters used
   16224    therein with the argument vector ARGS.  IN_DECL is an associated
   16225    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
   16226    Issue error and warning messages under control of COMPLAIN.  Note
   16227    that we must be relatively non-tolerant of extensions here, in
   16228    order to preserve conformance; if we allow substitutions that
   16229    should not be allowed, we may allow argument deductions that should
   16230    not succeed, and therefore report ambiguous overload situations
   16231    where there are none.  In theory, we could allow the substitution,
   16232    but indicate that it should have failed, and allow our caller to
   16233    make sure that the right thing happens, but we don't try to do this
   16234    yet.
   16235 
   16236    This function is used for dealing with types, decls and the like;
   16237    for expressions, use tsubst_expr or tsubst_copy.  */
   16238 
   16239 tree
   16240 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
   16241 {
   16242   enum tree_code code;
   16243   tree type, r = NULL_TREE;
   16244 
   16245   if (t == NULL_TREE || t == error_mark_node
   16246       || t == integer_type_node
   16247       || t == void_type_node
   16248       || t == char_type_node
   16249       || t == unknown_type_node
   16250       || TREE_CODE (t) == NAMESPACE_DECL
   16251       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
   16252     return t;
   16253 
   16254   tsubst_flags_t tst_ok_flag = (complain & tf_tst_ok);
   16255   complain &= ~tf_tst_ok;
   16256 
   16257   tsubst_flags_t qualifying_scope_flag = (complain & tf_qualifying_scope);
   16258   complain &= ~tf_qualifying_scope;
   16259 
   16260   if (DECL_P (t))
   16261     return tsubst_decl (t, args, complain);
   16262 
   16263   if (args == NULL_TREE)
   16264     return t;
   16265 
   16266   code = TREE_CODE (t);
   16267 
   16268   gcc_assert (code != IDENTIFIER_NODE);
   16269   type = TREE_TYPE (t);
   16270 
   16271   gcc_assert (type != unknown_type_node);
   16272 
   16273   if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
   16274     return d;
   16275 
   16276   /* Reuse typedefs.  We need to do this to handle dependent attributes,
   16277      such as attribute aligned.  */
   16278   if (TYPE_P (t)
   16279       && typedef_variant_p (t))
   16280     {
   16281       tree decl = TYPE_NAME (t);
   16282 
   16283       if (alias_template_specialization_p (t, nt_opaque))
   16284 	{
   16285 	  /* DECL represents an alias template and we want to
   16286 	     instantiate it.  */
   16287 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
   16288 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
   16289 	  r = instantiate_alias_template (tmpl, gen_args, complain);
   16290 	}
   16291       else if (DECL_CLASS_SCOPE_P (decl)
   16292 	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
   16293 	       && uses_template_parms (DECL_CONTEXT (decl)))
   16294 	{
   16295 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
   16296 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
   16297 	  r = retrieve_specialization (tmpl, gen_args, 0);
   16298 	}
   16299       else if (DECL_FUNCTION_SCOPE_P (decl)
   16300 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
   16301 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
   16302 	r = retrieve_local_specialization (decl);
   16303       else
   16304 	/* The typedef is from a non-template context.  */
   16305 	return t;
   16306 
   16307       if (r)
   16308 	{
   16309 	  r = TREE_TYPE (r);
   16310 	  r = cp_build_qualified_type
   16311 	    (r, cp_type_quals (t) | cp_type_quals (r),
   16312 	     complain | tf_ignore_bad_quals);
   16313 	  return r;
   16314 	}
   16315       else
   16316 	{
   16317 	  /* We don't have an instantiation yet, so drop the typedef.  */
   16318 	  int quals = cp_type_quals (t);
   16319 	  t = DECL_ORIGINAL_TYPE (decl);
   16320 	  t = cp_build_qualified_type (t, quals,
   16321 				       complain | tf_ignore_bad_quals);
   16322 	}
   16323     }
   16324 
   16325   bool fndecl_type = (complain & tf_fndecl_type);
   16326   complain &= ~tf_fndecl_type;
   16327 
   16328   if (type
   16329       && code != TYPENAME_TYPE
   16330       && code != TEMPLATE_TYPE_PARM
   16331       && code != TEMPLATE_PARM_INDEX
   16332       && code != IDENTIFIER_NODE
   16333       && code != FUNCTION_TYPE
   16334       && code != METHOD_TYPE)
   16335     type = tsubst (type, args, complain, in_decl);
   16336   if (type == error_mark_node)
   16337     return error_mark_node;
   16338 
   16339   switch (code)
   16340     {
   16341     case RECORD_TYPE:
   16342       if (TYPE_PTRMEMFUNC_P (t))
   16343 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
   16344       /* Fall through.  */
   16345     case UNION_TYPE:
   16346     case ENUMERAL_TYPE:
   16347       return tsubst_aggr_type_1 (t, args, complain, in_decl,
   16348 				 /*entering_scope=*/0);
   16349 
   16350     case ERROR_MARK:
   16351     case IDENTIFIER_NODE:
   16352     case VOID_TYPE:
   16353     case OPAQUE_TYPE:
   16354     case REAL_TYPE:
   16355     case COMPLEX_TYPE:
   16356     case VECTOR_TYPE:
   16357     case BOOLEAN_TYPE:
   16358     case NULLPTR_TYPE:
   16359     case LANG_TYPE:
   16360       return t;
   16361 
   16362     case INTEGER_TYPE:
   16363       if (t == integer_type_node)
   16364 	return t;
   16365 
   16366       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
   16367           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
   16368         return t;
   16369 
   16370       {
   16371 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
   16372 
   16373 	max = tsubst_expr (omax, args, complain, in_decl);
   16374 
   16375 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
   16376 	   needed.  */
   16377 	if (TREE_CODE (max) == NOP_EXPR
   16378 	    && TREE_SIDE_EFFECTS (omax)
   16379 	    && !TREE_TYPE (max))
   16380 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
   16381 
   16382 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
   16383 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
   16384 	   constant expression.  */
   16385 	if (processing_template_decl
   16386 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
   16387 	  {
   16388 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
   16389 	    TREE_SIDE_EFFECTS (max) = 1;
   16390 	  }
   16391 
   16392 	return compute_array_index_type (NULL_TREE, max, complain);
   16393       }
   16394 
   16395     case TEMPLATE_TYPE_PARM:
   16396       if (TEMPLATE_TYPE_LEVEL (t) == 0)
   16397 	{
   16398 	  /* This is either an ordinary level-less auto or a CTAD placeholder
   16399 	     auto.  These get replaced only via do_auto_deduction which, in the
   16400 	     ordinary case, temporarily overrides its level to 1 before calling
   16401 	     tsubst.  CTAD placeholders are replaced via do_class_deduction.  */
   16402 	  gcc_checking_assert (is_auto (t));
   16403 	  tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (t);
   16404 	  if (!tmpl)
   16405 	    /* Ordinary level-less auto has nothing to substitute.  */
   16406 	    return t;
   16407 
   16408 	  /* Substitute the template of this CTAD placeholder.  */
   16409 	  tmpl = tsubst_expr (tmpl, args, complain, in_decl);
   16410 	  if (TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
   16411 	    tmpl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (tmpl);
   16412 
   16413 	  if (tmpl != CLASS_PLACEHOLDER_TEMPLATE (t))
   16414 	    return make_template_placeholder (tmpl);
   16415 	  else
   16416 	    return t;
   16417 	}
   16418       /* Fall through.  */
   16419     case TEMPLATE_TEMPLATE_PARM:
   16420     case BOUND_TEMPLATE_TEMPLATE_PARM:
   16421     case TEMPLATE_PARM_INDEX:
   16422       {
   16423 	int idx;
   16424 	int level;
   16425 	int levels;
   16426 	tree arg = NULL_TREE;
   16427 
   16428 	r = NULL_TREE;
   16429 
   16430 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
   16431 	template_parm_level_and_index (t, &level, &idx);
   16432 
   16433 	levels = TMPL_ARGS_DEPTH (args);
   16434 	if (level <= levels
   16435 	    && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
   16436 	  {
   16437 	    arg = TMPL_ARG (args, level, idx);
   16438 
   16439 	    /* See through ARGUMENT_PACK_SELECT arguments. */
   16440 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
   16441 	      arg = argument_pack_select_arg (arg);
   16442 	  }
   16443 
   16444 	if (arg == error_mark_node)
   16445 	  return error_mark_node;
   16446 	else if (arg != NULL_TREE)
   16447 	  {
   16448 	    if (ARGUMENT_PACK_P (arg))
   16449 	      /* If ARG is an argument pack, we don't actually want to
   16450 		 perform a substitution here, because substitutions
   16451 		 for argument packs are only done
   16452 		 element-by-element. We can get to this point when
   16453 		 substituting the type of a non-type template
   16454 		 parameter pack, when that type actually contains
   16455 		 template parameter packs from an outer template, e.g.,
   16456 
   16457 	         template<typename... Types> struct A {
   16458 		   template<Types... Values> struct B { };
   16459                  };  */
   16460 	      return t;
   16461 
   16462 	    if (code == TEMPLATE_TYPE_PARM)
   16463 	      {
   16464 		int quals;
   16465 
   16466 		/* When building concept checks for the purpose of
   16467 		   deducing placeholders, we can end up with wildcards
   16468 		   where types are expected. Adjust this to the deduced
   16469 		   value.  */
   16470 		if (TREE_CODE (arg) == WILDCARD_DECL)
   16471 		  arg = TREE_TYPE (TREE_TYPE (arg));
   16472 
   16473 		gcc_assert (TYPE_P (arg));
   16474 
   16475 		quals = cp_type_quals (arg) | cp_type_quals (t);
   16476 
   16477 		return cp_build_qualified_type
   16478 		  (arg, quals, complain | tf_ignore_bad_quals);
   16479 	      }
   16480 	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
   16481 	      {
   16482 		/* We are processing a type constructed from a
   16483 		   template template parameter.  */
   16484 		tree argvec = tsubst (TYPE_TI_ARGS (t),
   16485 				      args, complain, in_decl);
   16486 		if (argvec == error_mark_node)
   16487 		  return error_mark_node;
   16488 
   16489 		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
   16490 			    || TREE_CODE (arg) == TEMPLATE_DECL
   16491 			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
   16492 
   16493 		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
   16494 		  /* Consider this code:
   16495 
   16496 			template <template <class> class Template>
   16497 			struct Internal {
   16498 			template <class Arg> using Bind = Template<Arg>;
   16499 			};
   16500 
   16501 			template <template <class> class Template, class Arg>
   16502 			using Instantiate = Template<Arg>; //#0
   16503 
   16504 			template <template <class> class Template,
   16505                                   class Argument>
   16506 			using Bind =
   16507 			  Instantiate<Internal<Template>::template Bind,
   16508 				      Argument>; //#1
   16509 
   16510 		     When #1 is parsed, the
   16511 		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
   16512 		     parameter `Template' in #0 matches the
   16513 		     UNBOUND_CLASS_TEMPLATE representing the argument
   16514 		     `Internal<Template>::template Bind'; We then want
   16515 		     to assemble the type `Bind<Argument>' that can't
   16516 		     be fully created right now, because
   16517 		     `Internal<Template>' not being complete, the Bind
   16518 		     template cannot be looked up in that context.  So
   16519 		     we need to "store" `Bind<Argument>' for later
   16520 		     when the context of Bind becomes complete.  Let's
   16521 		     store that in a TYPENAME_TYPE.  */
   16522 		  return make_typename_type (TYPE_CONTEXT (arg),
   16523 					     build_nt (TEMPLATE_ID_EXPR,
   16524 						       TYPE_IDENTIFIER (arg),
   16525 						       argvec),
   16526 					     typename_type,
   16527 					     complain);
   16528 
   16529 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
   16530 		   are resolving nested-types in the signature of a
   16531 		   member function templates.  Otherwise ARG is a
   16532 		   TEMPLATE_DECL and is the real template to be
   16533 		   instantiated.  */
   16534 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
   16535 		  arg = TYPE_NAME (arg);
   16536 
   16537 		r = lookup_template_class (arg,
   16538 					   argvec, in_decl,
   16539 					   DECL_CONTEXT (arg),
   16540 					    /*entering_scope=*/0,
   16541 					   complain);
   16542 		return cp_build_qualified_type
   16543 		  (r, cp_type_quals (t) | cp_type_quals (r), complain);
   16544 	      }
   16545 	    else if (code == TEMPLATE_TEMPLATE_PARM)
   16546 	      return arg;
   16547 	    else
   16548 	      /* TEMPLATE_PARM_INDEX.  */
   16549 	      return convert_from_reference (unshare_expr (arg));
   16550 	  }
   16551 
   16552 	if (level == 1)
   16553 	  /* This can happen during the attempted tsubst'ing in
   16554 	     unify.  This means that we don't yet have any information
   16555 	     about the template parameter in question.  */
   16556 	  return t;
   16557 
   16558 	/* Early in template argument deduction substitution, we don't
   16559 	   want to reduce the level of 'auto', or it will be confused
   16560 	   with a normal template parm in subsequent deduction.
   16561 	   Similarly, don't reduce the level of template parameters to
   16562 	   avoid mismatches when deducing their types.  */
   16563 	if (complain & tf_partial)
   16564 	  return t;
   16565 
   16566 	/* If we get here, we must have been looking at a parm for a
   16567 	   more deeply nested template.  Make a new version of this
   16568 	   template parameter, but with a lower level.  */
   16569 	int quals;
   16570 	switch (code)
   16571 	  {
   16572 	  case TEMPLATE_TYPE_PARM:
   16573 	  case TEMPLATE_TEMPLATE_PARM:
   16574 	    quals = cp_type_quals (t);
   16575 	    if (quals)
   16576 	      {
   16577 		gcc_checking_assert (code == TEMPLATE_TYPE_PARM);
   16578 		t = TYPE_MAIN_VARIANT (t);
   16579 	      }
   16580 
   16581 	    if (tree d = TEMPLATE_TYPE_DESCENDANTS (t))
   16582 	      if (TEMPLATE_PARM_LEVEL (d) == TEMPLATE_TYPE_LEVEL (t) - levels
   16583 		  && (code == TEMPLATE_TYPE_PARM
   16584 		      || TEMPLATE_TEMPLATE_PARM_SIMPLE_P (t)))
   16585 		/* Cache lowering a type parameter or a simple template
   16586 		   template parameter.  */
   16587 		r = TREE_TYPE (d);
   16588 
   16589 	    if (!r)
   16590 	      {
   16591 		r = copy_type (t);
   16592 		TEMPLATE_TYPE_PARM_INDEX (r)
   16593 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
   16594 						r, levels, args, complain);
   16595 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
   16596 		TYPE_MAIN_VARIANT (r) = r;
   16597 		TYPE_POINTER_TO (r) = NULL_TREE;
   16598 		TYPE_REFERENCE_TO (r) = NULL_TREE;
   16599 
   16600 		if (code == TEMPLATE_TYPE_PARM)
   16601 		  if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (t))
   16602 		    /* Propagate constraints on placeholders since they are
   16603 		       only instantiated during satisfaction.  */
   16604 		    PLACEHOLDER_TYPE_CONSTRAINTS_INFO (r) = ci;
   16605 
   16606 		if (TYPE_STRUCTURAL_EQUALITY_P (t))
   16607 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
   16608 		else
   16609 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
   16610 	      }
   16611 
   16612 	    if (quals)
   16613 	      r = cp_build_qualified_type (r, quals,
   16614 					   complain | tf_ignore_bad_quals);
   16615 	    break;
   16616 
   16617 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
   16618 	    {
   16619 	      tree tinfo = TYPE_TEMPLATE_INFO (t);
   16620 	      /* We might need to substitute into the types of non-type
   16621 		 template parameters.  This also lowers the level of
   16622 		 the ttp appropriately.  */
   16623 	      tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
   16624 				  complain, in_decl);
   16625 	      if (tmpl == error_mark_node)
   16626 		return error_mark_node;
   16627 	      tree argvec = tsubst (TI_ARGS (tinfo), args,
   16628 				    complain, in_decl);
   16629 	      if (argvec == error_mark_node)
   16630 		return error_mark_node;
   16631 	      r = lookup_template_class (tmpl, argvec, in_decl, NULL_TREE,
   16632 					 /*entering_scope=*/false, complain);
   16633 	      r = cp_build_qualified_type (r, cp_type_quals (t), complain);
   16634 	      break;
   16635 	    }
   16636 
   16637 	  case TEMPLATE_PARM_INDEX:
   16638 	    /* OK, now substitute the type of the non-type parameter.  We
   16639 	       couldn't do it earlier because it might be an auto parameter,
   16640 	       and we wouldn't need to if we had an argument.  */
   16641 	    type = tsubst (type, args, complain, in_decl);
   16642 	    if (type == error_mark_node)
   16643 	      return error_mark_node;
   16644 	    r = reduce_template_parm_level (t, type, levels, args, complain);
   16645 	    break;
   16646 
   16647 	  default:
   16648 	    gcc_unreachable ();
   16649 	  }
   16650 
   16651 	return r;
   16652       }
   16653 
   16654     case TREE_LIST:
   16655       return tsubst_tree_list (t, args, complain, in_decl);
   16656 
   16657     case TREE_BINFO:
   16658       /* We should never be tsubsting a binfo.  */
   16659       gcc_unreachable ();
   16660 
   16661     case TREE_VEC:
   16662       /* A vector of template arguments.  */
   16663       gcc_assert (!type);
   16664       return tsubst_template_args (t, args, complain, in_decl);
   16665 
   16666     case POINTER_TYPE:
   16667     case REFERENCE_TYPE:
   16668       {
   16669 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
   16670 	  return t;
   16671 
   16672 	/* [temp.deduct]
   16673 
   16674 	   Type deduction may fail for any of the following
   16675 	   reasons:
   16676 
   16677 	   -- Attempting to create a pointer to reference type.
   16678 	   -- Attempting to create a reference to a reference type or
   16679 	      a reference to void.
   16680 
   16681 	  Core issue 106 says that creating a reference to a reference
   16682 	  during instantiation is no longer a cause for failure. We
   16683 	  only enforce this check in strict C++98 mode.  */
   16684 	if ((TYPE_REF_P (type)
   16685 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
   16686 	    || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
   16687 	  {
   16688 	    static location_t last_loc;
   16689 
   16690 	    /* We keep track of the last time we issued this error
   16691 	       message to avoid spewing a ton of messages during a
   16692 	       single bad template instantiation.  */
   16693 	    if (complain & tf_error
   16694 		&& last_loc != input_location)
   16695 	      {
   16696 		if (VOID_TYPE_P (type))
   16697 		  error ("forming reference to void");
   16698                else if (code == POINTER_TYPE)
   16699                  error ("forming pointer to reference type %qT", type);
   16700                else
   16701 		  error ("forming reference to reference type %qT", type);
   16702 		last_loc = input_location;
   16703 	      }
   16704 
   16705 	    return error_mark_node;
   16706 	  }
   16707 	else if (TREE_CODE (type) == FUNCTION_TYPE
   16708 		 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
   16709 		     || type_memfn_rqual (type) != REF_QUAL_NONE))
   16710 	  {
   16711 	    if (complain & tf_error)
   16712 	      {
   16713 		if (code == POINTER_TYPE)
   16714 		  error ("forming pointer to qualified function type %qT",
   16715 			 type);
   16716 		else
   16717 		  error ("forming reference to qualified function type %qT",
   16718 			 type);
   16719 	      }
   16720 	    return error_mark_node;
   16721 	  }
   16722 	else if (code == POINTER_TYPE)
   16723 	  {
   16724 	    r = build_pointer_type (type);
   16725 	    if (TREE_CODE (type) == METHOD_TYPE)
   16726 	      r = build_ptrmemfunc_type (r);
   16727 	  }
   16728 	else if (TYPE_REF_P (type))
   16729 	  /* In C++0x, during template argument substitution, when there is an
   16730 	     attempt to create a reference to a reference type, reference
   16731 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
   16732 
   16733 	     "If a template-argument for a template-parameter T names a type
   16734 	     that is a reference to a type A, an attempt to create the type
   16735 	     'lvalue reference to cv T' creates the type 'lvalue reference to
   16736 	     A,' while an attempt to create the type type rvalue reference to
   16737 	     cv T' creates the type T"
   16738 	  */
   16739 	  r = cp_build_reference_type
   16740 	      (TREE_TYPE (type),
   16741 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
   16742 	else
   16743 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
   16744 	r = cp_build_qualified_type (r, cp_type_quals (t), complain);
   16745 
   16746 	if (r != error_mark_node)
   16747 	  /* Will this ever be needed for TYPE_..._TO values?  */
   16748 	  layout_type (r);
   16749 
   16750 	return r;
   16751       }
   16752     case OFFSET_TYPE:
   16753       {
   16754 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
   16755 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
   16756 	  {
   16757 	    /* [temp.deduct]
   16758 
   16759 	       Type deduction may fail for any of the following
   16760 	       reasons:
   16761 
   16762 	       -- Attempting to create "pointer to member of T" when T
   16763 		  is not a class type.  */
   16764 	    if (complain & tf_error)
   16765 	      error ("creating pointer to member of non-class type %qT", r);
   16766 	    return error_mark_node;
   16767 	  }
   16768 	if (TYPE_REF_P (type))
   16769 	  {
   16770 	    if (complain & tf_error)
   16771 	      error ("creating pointer to member reference type %qT", type);
   16772 	    return error_mark_node;
   16773 	  }
   16774 	if (VOID_TYPE_P (type))
   16775 	  {
   16776 	    if (complain & tf_error)
   16777 	      error ("creating pointer to member of type void");
   16778 	    return error_mark_node;
   16779 	  }
   16780 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
   16781 	if (TREE_CODE (type) == FUNCTION_TYPE)
   16782 	  {
   16783 	    /* The type of the implicit object parameter gets its
   16784 	       cv-qualifiers from the FUNCTION_TYPE. */
   16785 	    tree memptr;
   16786 	    tree method_type
   16787 	      = build_memfn_type (type, r, type_memfn_quals (type),
   16788 				  type_memfn_rqual (type));
   16789 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
   16790 	    return cp_build_qualified_type (memptr, cp_type_quals (t),
   16791 					    complain);
   16792 	  }
   16793 	else
   16794 	  return cp_build_qualified_type (build_ptrmem_type (r, type),
   16795 					  cp_type_quals (t),
   16796 					  complain);
   16797       }
   16798     case FUNCTION_TYPE:
   16799     case METHOD_TYPE:
   16800       {
   16801 	tree fntype;
   16802 	tree specs;
   16803 	fntype = tsubst_function_type (t, args, complain, in_decl);
   16804 	if (fntype == error_mark_node)
   16805 	  return error_mark_node;
   16806 
   16807 	/* Substitute the exception specification.  */
   16808 	specs = tsubst_exception_specification (t, args, complain, in_decl,
   16809 						/*defer_ok*/fndecl_type);
   16810 	if (specs == error_mark_node)
   16811 	  return error_mark_node;
   16812 	if (specs)
   16813 	  fntype = build_exception_variant (fntype, specs);
   16814 	return fntype;
   16815       }
   16816     case ARRAY_TYPE:
   16817       {
   16818 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
   16819 	if (domain == error_mark_node)
   16820 	  return error_mark_node;
   16821 
   16822 	/* As an optimization, we avoid regenerating the array type if
   16823 	   it will obviously be the same as T.  */
   16824 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
   16825 	  return t;
   16826 
   16827 	/* These checks should match the ones in create_array_type_for_decl.
   16828 
   16829 	   [temp.deduct]
   16830 
   16831 	   The deduction may fail for any of the following reasons:
   16832 
   16833 	   -- Attempting to create an array with an element type that
   16834 	      is void, a function type, or a reference type, or [DR337]
   16835 	      an abstract class type.  */
   16836 	if (VOID_TYPE_P (type)
   16837 	    || TREE_CODE (type) == FUNCTION_TYPE
   16838 	    || (TREE_CODE (type) == ARRAY_TYPE
   16839 		&& TYPE_DOMAIN (type) == NULL_TREE)
   16840 	    || TYPE_REF_P (type))
   16841 	  {
   16842 	    if (complain & tf_error)
   16843 	      error ("creating array of %qT", type);
   16844 	    return error_mark_node;
   16845 	  }
   16846 
   16847 	if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
   16848 				  !(complain & tf_error)))
   16849 	  return error_mark_node;
   16850 
   16851 	r = build_cplus_array_type (type, domain);
   16852 
   16853 	if (!valid_array_size_p (input_location, r, in_decl,
   16854 				 (complain & tf_error)))
   16855 	  return error_mark_node;
   16856 
   16857 	if (TYPE_USER_ALIGN (t))
   16858 	  {
   16859 	    SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
   16860 	    TYPE_USER_ALIGN (r) = 1;
   16861 	  }
   16862 
   16863 	return r;
   16864       }
   16865 
   16866     case TYPENAME_TYPE:
   16867       {
   16868 	tree ctx = TYPE_CONTEXT (t);
   16869 	if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
   16870 	  {
   16871 	    ctx = tsubst_pack_expansion (ctx, args,
   16872 					 complain | tf_qualifying_scope,
   16873 					 in_decl);
   16874 	    if (ctx == error_mark_node
   16875 		|| TREE_VEC_LENGTH (ctx) > 1)
   16876 	      return error_mark_node;
   16877 	    if (TREE_VEC_LENGTH (ctx) == 0)
   16878 	      {
   16879 		if (complain & tf_error)
   16880 		  error ("%qD is instantiated for an empty pack",
   16881 			 TYPENAME_TYPE_FULLNAME (t));
   16882 		return error_mark_node;
   16883 	      }
   16884 	    ctx = TREE_VEC_ELT (ctx, 0);
   16885 	  }
   16886 	else
   16887 	  ctx = tsubst_aggr_type (ctx, args,
   16888 				  complain | tf_qualifying_scope,
   16889 				  in_decl, /*entering_scope=*/1);
   16890 	if (ctx == error_mark_node)
   16891 	  return error_mark_node;
   16892 
   16893 	tree f = tsubst_name (TYPENAME_TYPE_FULLNAME (t), args,
   16894 			      complain, in_decl);
   16895 	if (f == error_mark_node)
   16896 	  return error_mark_node;
   16897 
   16898 	if (!MAYBE_CLASS_TYPE_P (ctx))
   16899 	  {
   16900 	    if (complain & tf_error)
   16901 	      error ("%qT is not a class, struct, or union type", ctx);
   16902 	    return error_mark_node;
   16903 	  }
   16904 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
   16905 	  {
   16906 	    /* Normally, make_typename_type does not require that the CTX
   16907 	       have complete type in order to allow things like:
   16908 
   16909 		 template <class T> struct S { typename S<T>::X Y; };
   16910 
   16911 	       But, such constructs have already been resolved by this
   16912 	       point, so here CTX really should have complete type, unless
   16913 	       it's a partial instantiation.  */
   16914 	    if (!complete_type_or_maybe_complain (ctx, NULL_TREE, complain))
   16915 	      return error_mark_node;
   16916 	  }
   16917 
   16918 	/* FIXME: TYPENAME_IS_CLASS_P conflates 'class' vs 'struct' vs 'union'
   16919 	   tags.  TYPENAME_TYPE should probably remember the exact tag that
   16920 	   was written.  */
   16921 	enum tag_types tag_type
   16922 	  = TYPENAME_IS_CLASS_P (t) ? class_type
   16923 	  : TYPENAME_IS_ENUM_P (t) ? enum_type
   16924 	  : typename_type;
   16925 	tsubst_flags_t tcomplain = complain | tf_keep_type_decl;
   16926 	tcomplain |= tst_ok_flag | qualifying_scope_flag;
   16927 	f = make_typename_type (ctx, f, tag_type, tcomplain);
   16928 	if (f == error_mark_node)
   16929 	  return f;
   16930 	if (TREE_CODE (f) == TYPE_DECL)
   16931 	  {
   16932 	    complain |= tf_ignore_bad_quals;
   16933 	    f = TREE_TYPE (f);
   16934 	  }
   16935 
   16936 	if (TREE_CODE (f) != TYPENAME_TYPE)
   16937 	  {
   16938 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
   16939 	      {
   16940 		if (complain & tf_error)
   16941 		  error ("%qT resolves to %qT, which is not an enumeration type",
   16942 			 t, f);
   16943 		else
   16944 		  return error_mark_node;
   16945 	      }
   16946 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
   16947 	      {
   16948 		if (complain & tf_error)
   16949 		  error ("%qT resolves to %qT, which is not a class type",
   16950 			 t, f);
   16951 		else
   16952 		  return error_mark_node;
   16953 	      }
   16954 	  }
   16955 
   16956 	return cp_build_qualified_type
   16957 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
   16958       }
   16959 
   16960     case UNBOUND_CLASS_TEMPLATE:
   16961       {
   16962 	tree name = TYPE_IDENTIFIER (t);
   16963 	if (name == error_mark_node)
   16964 	  return error_mark_node;
   16965 
   16966 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
   16967 	parm_list = tsubst_template_parms (parm_list, args, complain);
   16968 	if (parm_list == error_mark_node)
   16969 	  return error_mark_node;
   16970 
   16971 	if (parm_list && TMPL_PARMS_DEPTH (parm_list) > 1)
   16972 	  ++processing_template_decl;
   16973 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
   16974 				     in_decl, /*entering_scope=*/1);
   16975 	if (parm_list && TMPL_PARMS_DEPTH (parm_list) > 1)
   16976 	  --processing_template_decl;
   16977 	if (ctx == error_mark_node)
   16978 	  return error_mark_node;
   16979 
   16980 	return make_unbound_class_template (ctx, name, parm_list, complain);
   16981       }
   16982 
   16983     case TYPEOF_TYPE:
   16984       {
   16985 	tree type;
   16986 
   16987 	++cp_unevaluated_operand;
   16988 	++c_inhibit_evaluation_warnings;
   16989 
   16990 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args, complain, in_decl);
   16991 
   16992 	--cp_unevaluated_operand;
   16993 	--c_inhibit_evaluation_warnings;
   16994 
   16995 	type = finish_typeof (type);
   16996 	return cp_build_qualified_type (type,
   16997 					cp_type_quals (t)
   16998 					| cp_type_quals (type),
   16999 					complain);
   17000       }
   17001 
   17002     case DECLTYPE_TYPE:
   17003       {
   17004 	tree type;
   17005 
   17006 	++cp_unevaluated_operand;
   17007 	++c_inhibit_evaluation_warnings;
   17008 
   17009 	type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
   17010 			    complain|tf_decltype, in_decl);
   17011 
   17012 	--cp_unevaluated_operand;
   17013 	--c_inhibit_evaluation_warnings;
   17014 
   17015 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
   17016 	  type = lambda_capture_field_type (type,
   17017 					    false /*explicit_init*/,
   17018 					    DECLTYPE_FOR_REF_CAPTURE (t));
   17019 	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
   17020 	  type = lambda_proxy_type (type);
   17021 	else
   17022 	  {
   17023 	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
   17024 	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
   17025 		&& EXPR_P (type))
   17026 	      /* In a template ~id could be either a complement expression
   17027 		 or an unqualified-id naming a destructor; if instantiating
   17028 		 it produces an expression, it's not an id-expression or
   17029 		 member access.  */
   17030 	      id = false;
   17031 	    type = finish_decltype_type (type, id, complain);
   17032 	  }
   17033 	return cp_build_qualified_type (type,
   17034 					cp_type_quals (t)
   17035 					| cp_type_quals (type),
   17036 					complain | tf_ignore_bad_quals);
   17037       }
   17038 
   17039     case TRAIT_TYPE:
   17040       {
   17041 	tree type1 = TRAIT_TYPE_TYPE1 (t);
   17042 	if (TYPE_P (type1))
   17043 	  type1 = tsubst (type1, args, complain, in_decl);
   17044 	else
   17045 	  type1 = tsubst_expr (type1, args, complain, in_decl);
   17046 	tree type2 = tsubst (TRAIT_TYPE_TYPE2 (t), args, complain, in_decl);
   17047 	type = finish_trait_type (TRAIT_TYPE_KIND (t), type1, type2, complain);
   17048 	return cp_build_qualified_type (type,
   17049 					cp_type_quals (t) | cp_type_quals (type),
   17050 					complain | tf_ignore_bad_quals);
   17051       }
   17052 
   17053     case TYPE_ARGUMENT_PACK:
   17054     case NONTYPE_ARGUMENT_PACK:
   17055       return tsubst_argument_pack (t, args, complain, in_decl);
   17056 
   17057     case VOID_CST:
   17058     case INTEGER_CST:
   17059     case REAL_CST:
   17060     case STRING_CST:
   17061     case PLUS_EXPR:
   17062     case MINUS_EXPR:
   17063     case NEGATE_EXPR:
   17064     case NOP_EXPR:
   17065     case INDIRECT_REF:
   17066     case ADDR_EXPR:
   17067     case CALL_EXPR:
   17068     case ARRAY_REF:
   17069     case SCOPE_REF:
   17070     case OMP_ARRAY_SECTION:
   17071       /* We should use one of the expression tsubsts for these codes.  */
   17072       gcc_unreachable ();
   17073 
   17074     default:
   17075       sorry ("use of %qs in template", get_tree_code_name (code));
   17076       return error_mark_node;
   17077     }
   17078 }
   17079 
   17080 /* Convenience wrapper over tsubst for substituting into the LHS
   17081    of the :: scope resolution operator.  */
   17082 
   17083 static tree
   17084 tsubst_scope (tree t, tree args, tsubst_flags_t complain, tree in_decl)
   17085 {
   17086   gcc_checking_assert (TYPE_P (t));
   17087   return tsubst (t, args, complain | tf_qualifying_scope, in_decl);
   17088 }
   17089 
   17090 /* Convenience wrapper over tsubst for substituting into an id-expression
   17091    without resolving its terminal name.  */
   17092 
   17093 static tree
   17094 tsubst_name (tree t, tree args, tsubst_flags_t complain, tree in_decl)
   17095 {
   17096   return tsubst_expr (t, args, complain | tf_no_name_lookup, in_decl);
   17097 }
   17098 
   17099 /* OLDFNS is a lookup set of member functions from some class template, and
   17100    NEWFNS is a lookup set of member functions from NEWTYPE, a specialization
   17101    of that class template.  Return the subset of NEWFNS which are
   17102    specializations of a function from OLDFNS.  */
   17103 
   17104 static tree
   17105 filter_memfn_lookup (tree oldfns, tree newfns, tree newtype)
   17106 {
   17107   /* Record all member functions from the old lookup set OLDFNS into
   17108      VISIBLE_SET.  */
   17109   hash_set<tree> visible_set;
   17110   bool seen_dep_using = false;
   17111   for (tree fn : lkp_range (oldfns))
   17112     {
   17113       if (TREE_CODE (fn) == USING_DECL)
   17114 	{
   17115 	  /* Imprecisely handle dependent using-decl by keeping all members
   17116 	     in the new lookup set that are defined in a base class, i.e.
   17117 	     members that could plausibly have been introduced by this
   17118 	     dependent using-decl.
   17119 	     FIXME: Track which members are introduced by a dependent
   17120 	     using-decl precisely, perhaps by performing another lookup
   17121 	     from the substituted USING_DECL_SCOPE.  */
   17122 	  gcc_checking_assert (DECL_DEPENDENT_P (fn));
   17123 	  seen_dep_using = true;
   17124 	}
   17125       else
   17126 	visible_set.add (fn);
   17127     }
   17128 
   17129   /* Returns true iff (a less specialized version of) FN appeared in
   17130      the old lookup set OLDFNS.  */
   17131   auto visible_p = [newtype, seen_dep_using, &visible_set] (tree fn) {
   17132     if (DECL_CONTEXT (fn) != newtype)
   17133       /* FN is a member function from a base class, introduced via a
   17134 	 using-decl; if it might have been introduced by a dependent
   17135 	 using-decl then just conservatively keep it, otherwise look
   17136 	 in the old lookup set for FN exactly.  */
   17137       return seen_dep_using || visible_set.contains (fn);
   17138     else if (TREE_CODE (fn) == TEMPLATE_DECL)
   17139       /* FN is a member function template from the current class;
   17140 	 look in the old lookup set for the TEMPLATE_DECL from which
   17141 	 it was specialized.  */
   17142       return visible_set.contains (DECL_TI_TEMPLATE (fn));
   17143     else
   17144       /* FN is a non-template member function from the current class;
   17145 	 look in the old lookup set for the FUNCTION_DECL from which
   17146 	 it was specialized.  */
   17147       return visible_set.contains (DECL_TEMPLATE_RESULT
   17148 				   (DECL_TI_TEMPLATE (fn)));
   17149   };
   17150 
   17151   bool lookup_changed_p = false;
   17152   for (tree fn : lkp_range (newfns))
   17153     if (!visible_p (fn))
   17154       {
   17155 	lookup_changed_p = true;
   17156 	break;
   17157       }
   17158   if (!lookup_changed_p)
   17159     return newfns;
   17160 
   17161   /* Filter out from NEWFNS the member functions that weren't
   17162      previously visible according to OLDFNS.  */
   17163   tree filtered_fns = NULL_TREE;
   17164   unsigned filtered_size = 0;
   17165   for (tree fn : lkp_range (newfns))
   17166     if (visible_p (fn))
   17167       {
   17168 	filtered_fns = lookup_add (fn, filtered_fns);
   17169 	filtered_size++;
   17170       }
   17171   gcc_checking_assert (seen_dep_using
   17172 		       ? filtered_size >= visible_set.elements ()
   17173 		       : filtered_size == visible_set.elements ());
   17174 
   17175   return filtered_fns;
   17176 }
   17177 
   17178 /* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
   17179    expression on the left-hand side of the "." or "->" operator.  We
   17180    only do the lookup if we had a dependent BASELINK.  Otherwise we
   17181    adjust it onto the instantiated heirarchy.  */
   17182 
   17183 static tree
   17184 tsubst_baselink (tree baselink, tree object_type,
   17185 		 tree args, tsubst_flags_t complain, tree in_decl)
   17186 {
   17187   bool qualified_p = BASELINK_QUALIFIED_P (baselink);
   17188   tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
   17189   qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
   17190 
   17191   tree optype = BASELINK_OPTYPE (baselink);
   17192   optype = tsubst (optype, args, complain, in_decl);
   17193 
   17194   tree template_args = NULL_TREE;
   17195   bool template_id_p = false;
   17196   tree fns = BASELINK_FUNCTIONS (baselink);
   17197   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
   17198     {
   17199       template_id_p = true;
   17200       template_args = TREE_OPERAND (fns, 1);
   17201       fns = TREE_OPERAND (fns, 0);
   17202       if (template_args)
   17203 	template_args = tsubst_template_args (template_args, args,
   17204 					      complain, in_decl);
   17205     }
   17206 
   17207   tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
   17208   binfo_type = tsubst (binfo_type, args, complain, in_decl);
   17209   bool dependent_p = (binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink))
   17210 		      || optype != BASELINK_OPTYPE (baselink));
   17211 
   17212   if (dependent_p)
   17213     {
   17214       tree name = OVL_NAME (fns);
   17215       if (IDENTIFIER_CONV_OP_P (name))
   17216 	name = make_conv_op_name (optype);
   17217 
   17218       /* See maybe_dependent_member_ref.  */
   17219       if ((complain & tf_dguide) && dependent_scope_p (qualifying_scope))
   17220 	{
   17221 	  if (template_id_p)
   17222 	    name = build2 (TEMPLATE_ID_EXPR, unknown_type_node, name,
   17223 			   template_args);
   17224 	  return build_qualified_name (NULL_TREE, qualifying_scope, name,
   17225 				       /* ::template */false);
   17226 	}
   17227 
   17228       if (name == complete_dtor_identifier)
   17229 	/* Treat as-if non-dependent below.  */
   17230 	dependent_p = false;
   17231 
   17232       bool maybe_incomplete = BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink);
   17233       baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1,
   17234 				  complain);
   17235       if (!baselink)
   17236 	{
   17237 	  if ((complain & tf_error)
   17238 	      && constructor_name_p (name, qualifying_scope))
   17239 	    error ("cannot call constructor %<%T::%D%> directly",
   17240 		   qualifying_scope, name);
   17241 	  return error_mark_node;
   17242 	}
   17243 
   17244       if (maybe_incomplete)
   17245 	{
   17246 	  /* Filter out from the new lookup set those functions which didn't
   17247 	     appear in the original lookup set (in a less specialized form).
   17248 	     This is needed to preserve the consistency of member lookup
   17249 	     performed in an incomplete-class context, within which
   17250 	     later-declared members ought to remain invisible.  */
   17251 	  BASELINK_FUNCTIONS (baselink)
   17252 	    = filter_memfn_lookup (fns, BASELINK_FUNCTIONS (baselink),
   17253 				   binfo_type);
   17254 	  BASELINK_FUNCTIONS_MAYBE_INCOMPLETE_P (baselink) = true;
   17255 	}
   17256 
   17257       fns = BASELINK_FUNCTIONS (baselink);
   17258     }
   17259   else
   17260     {
   17261       /* We're going to overwrite pieces below, make a duplicate.  */
   17262       baselink = copy_node (baselink);
   17263 
   17264       if (qualifying_scope != BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink)))
   17265 	{
   17266 	  /* The decl we found was from non-dependent scope, but we still need
   17267 	     to update the binfos for the instantiated qualifying_scope.  */
   17268 	  BASELINK_ACCESS_BINFO (baselink) = TYPE_BINFO (qualifying_scope);
   17269 	  BASELINK_BINFO (baselink) = lookup_base (qualifying_scope, binfo_type,
   17270 						   ba_unique, nullptr, complain);
   17271 	}
   17272     }
   17273 
   17274   /* If lookup found a single function, mark it as used at this point.
   17275      (If lookup found multiple functions the one selected later by
   17276      overload resolution will be marked as used at that point.)  */
   17277   if (!template_id_p && !really_overloaded_fn (fns))
   17278     {
   17279       tree fn = OVL_FIRST (fns);
   17280       bool ok = mark_used (fn, complain);
   17281       if (!ok && !(complain & tf_error))
   17282 	return error_mark_node;
   17283       if (ok && BASELINK_P (baselink))
   17284 	/* We might have instantiated an auto function.  */
   17285 	TREE_TYPE (baselink) = TREE_TYPE (fn);
   17286     }
   17287 
   17288   if (BASELINK_P (baselink))
   17289     {
   17290       /* Add back the template arguments, if present.  */
   17291       if (template_id_p)
   17292 	BASELINK_FUNCTIONS (baselink)
   17293 	  = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
   17294 
   17295       /* Update the conversion operator type.  */
   17296       BASELINK_OPTYPE (baselink) = optype;
   17297     }
   17298 
   17299   if (!object_type)
   17300     object_type = current_class_type;
   17301 
   17302   if (qualified_p || !dependent_p)
   17303     {
   17304       baselink = adjust_result_of_qualified_name_lookup (baselink,
   17305 							 qualifying_scope,
   17306 							 object_type);
   17307       if (!qualified_p)
   17308 	/* We need to call adjust_result_of_qualified_name_lookup in case the
   17309 	   destructor names a base class, but we unset BASELINK_QUALIFIED_P
   17310 	   so that we still get virtual function binding.  */
   17311 	BASELINK_QUALIFIED_P (baselink) = false;
   17312     }
   17313 
   17314   return baselink;
   17315 }
   17316 
   17317 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
   17318    true if the qualified-id will be a postfix-expression in-and-of
   17319    itself; false if more of the postfix-expression follows the
   17320    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
   17321    of "&".  */
   17322 
   17323 static tree
   17324 tsubst_qualified_id (tree qualified_id, tree args,
   17325 		     tsubst_flags_t complain, tree in_decl,
   17326 		     bool done, bool address_p)
   17327 {
   17328   tree expr;
   17329   tree scope;
   17330   tree name;
   17331   bool is_template;
   17332   tree template_args;
   17333   location_t loc = EXPR_LOCATION (qualified_id);
   17334 
   17335   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
   17336 
   17337   /* Figure out what name to look up.  */
   17338   name = TREE_OPERAND (qualified_id, 1);
   17339   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
   17340     {
   17341       is_template = true;
   17342       template_args = TREE_OPERAND (name, 1);
   17343       if (template_args)
   17344 	template_args = tsubst_template_args (template_args, args,
   17345 					      complain, in_decl);
   17346       if (template_args == error_mark_node)
   17347 	return error_mark_node;
   17348       name = TREE_OPERAND (name, 0);
   17349     }
   17350   else
   17351     {
   17352       is_template = false;
   17353       template_args = NULL_TREE;
   17354     }
   17355 
   17356   /* Substitute into the qualifying scope.  When there are no ARGS, we
   17357      are just trying to simplify a non-dependent expression.  In that
   17358      case the qualifying scope may be dependent, and, in any case,
   17359      substituting will not help.  */
   17360   scope = TREE_OPERAND (qualified_id, 0);
   17361   if (args)
   17362     {
   17363       scope = tsubst_scope (scope, args, complain, in_decl);
   17364       expr = tsubst_name (name, args, complain, in_decl);
   17365     }
   17366   else
   17367     expr = name;
   17368 
   17369   if (dependent_scope_p (scope))
   17370     {
   17371       if (TREE_CODE (expr) == SCOPE_REF)
   17372 	/* We built one in tsubst_baselink.  */
   17373 	gcc_checking_assert (same_type_p (scope, TREE_OPERAND (expr, 0)));
   17374       else
   17375 	{
   17376 	  if (is_template)
   17377 	    expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr,
   17378 				     template_args);
   17379 	  expr = build_qualified_name (NULL_TREE, scope, expr,
   17380 				       QUALIFIED_NAME_IS_TEMPLATE
   17381 				       (qualified_id));
   17382 	}
   17383       REF_PARENTHESIZED_P (expr) = REF_PARENTHESIZED_P (qualified_id);
   17384       return expr;
   17385     }
   17386 
   17387   if (!BASELINK_P (name) && !DECL_P (expr))
   17388     {
   17389       if (TREE_CODE (expr) == BIT_NOT_EXPR)
   17390 	{
   17391 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
   17392 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
   17393 	    {
   17394 	      error ("qualifying type %qT does not match destructor name ~%qT",
   17395 		     scope, TREE_OPERAND (expr, 0));
   17396 	      expr = error_mark_node;
   17397 	    }
   17398 	  else
   17399 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
   17400 					  LOOK_want::NORMAL, false);
   17401 	}
   17402       else
   17403 	expr = lookup_qualified_name (scope, expr, LOOK_want::NORMAL, false);
   17404       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
   17405 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
   17406 	{
   17407 	  if (complain & tf_error)
   17408 	    {
   17409 	      error ("dependent-name %qE is parsed as a non-type, but "
   17410 		     "instantiation yields a type", qualified_id);
   17411 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
   17412 	    }
   17413 	  return error_mark_node;
   17414 	}
   17415     }
   17416 
   17417   if (DECL_P (expr))
   17418     {
   17419       if (!check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
   17420 						scope, complain))
   17421 	return error_mark_node;
   17422       /* Remember that there was a reference to this entity.  */
   17423       if (!mark_used (expr, complain) && !(complain & tf_error))
   17424 	return error_mark_node;
   17425     }
   17426 
   17427   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
   17428     {
   17429       if (complain & tf_error)
   17430 	qualified_name_lookup_error (scope,
   17431 				     TREE_OPERAND (qualified_id, 1),
   17432 				     expr, input_location);
   17433       return error_mark_node;
   17434     }
   17435 
   17436   if (is_template)
   17437     {
   17438       /* We may be repeating a check already done during parsing, but
   17439 	 if it was well-formed and passed then, it will pass again
   17440 	 now, and if it didn't, we wouldn't have got here.  The case
   17441 	 we want to catch is when we couldn't tell then, and can now,
   17442 	 namely when templ prior to substitution was an
   17443 	 identifier.  */
   17444       if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
   17445 	return error_mark_node;
   17446 
   17447       if (variable_template_p (expr))
   17448 	expr = lookup_and_finish_template_variable (expr, template_args,
   17449 						    complain);
   17450       else
   17451 	expr = lookup_template_function (expr, template_args);
   17452     }
   17453 
   17454   if (expr == error_mark_node && complain & tf_error)
   17455     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
   17456 				 expr, input_location);
   17457   else if (TYPE_P (scope))
   17458     {
   17459       expr = (adjust_result_of_qualified_name_lookup
   17460 	      (expr, scope, current_nonlambda_class_type ()));
   17461       expr = (finish_qualified_id_expr
   17462 	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
   17463 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
   17464 	       /*template_arg_p=*/false, complain));
   17465     }
   17466 
   17467   /* Expressions do not generally have reference type.  */
   17468   if (TREE_CODE (expr) != SCOPE_REF
   17469       /* However, if we're about to form a pointer-to-member, we just
   17470 	 want the referenced member referenced.  */
   17471       && TREE_CODE (expr) != OFFSET_REF)
   17472     expr = convert_from_reference (expr);
   17473 
   17474   if (REF_PARENTHESIZED_P (qualified_id))
   17475     expr = force_paren_expr (expr);
   17476 
   17477   expr = maybe_wrap_with_location (expr, loc);
   17478 
   17479   return expr;
   17480 }
   17481 
   17482 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
   17483    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
   17484    for tsubst.  */
   17485 
   17486 static tree
   17487 tsubst_init (tree init, tree decl, tree args,
   17488 	     tsubst_flags_t complain, tree in_decl)
   17489 {
   17490   if (!init)
   17491     return NULL_TREE;
   17492 
   17493   init = tsubst_expr (init, args, complain, in_decl);
   17494 
   17495   tree type = TREE_TYPE (decl);
   17496 
   17497   if (!init && type != error_mark_node)
   17498     {
   17499       if (tree auto_node = type_uses_auto (type))
   17500 	{
   17501 	  if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
   17502 	    {
   17503 	      if (complain & tf_error)
   17504 		error ("initializer for %q#D expands to an empty list "
   17505 		       "of expressions", decl);
   17506 	      return error_mark_node;
   17507 	    }
   17508 	}
   17509       else if (!dependent_type_p (type))
   17510 	{
   17511 	  /* If we had an initializer but it
   17512 	     instantiated to nothing,
   17513 	     value-initialize the object.  This will
   17514 	     only occur when the initializer was a
   17515 	     pack expansion where the parameter packs
   17516 	     used in that expansion were of length
   17517 	     zero.  */
   17518 	  init = build_value_init (type, complain);
   17519 	  if (TREE_CODE (init) == AGGR_INIT_EXPR)
   17520 	    init = get_target_expr (init, complain);
   17521 	  if (TREE_CODE (init) == TARGET_EXPR)
   17522 	    TARGET_EXPR_DIRECT_INIT_P (init) = true;
   17523 	}
   17524     }
   17525 
   17526   return init;
   17527 }
   17528 
   17529 /* If T is a reference to a dependent member of the current instantiation C and
   17530    we are trying to refer to that member in a partial instantiation of C,
   17531    return a SCOPE_REF; otherwise, return NULL_TREE.
   17532 
   17533    This can happen when forming a C++17 deduction guide, as in PR96199.  */
   17534 
   17535 static tree
   17536 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
   17537 			    tree in_decl)
   17538 {
   17539   if (!(complain & tf_dguide))
   17540     return NULL_TREE;
   17541 
   17542   tree decl = (t && TYPE_P (t)) ? TYPE_NAME (t) : t;
   17543   if (!decl || !DECL_P (decl))
   17544     return NULL_TREE;
   17545 
   17546   tree ctx = context_for_name_lookup (decl);
   17547   if (!CLASS_TYPE_P (ctx))
   17548     return NULL_TREE;
   17549 
   17550   ctx = tsubst (ctx, args, complain, in_decl);
   17551   if (!dependent_scope_p (ctx))
   17552     return NULL_TREE;
   17553 
   17554   if (TYPE_P (t))
   17555     {
   17556       if (typedef_variant_p (t))
   17557 	t = strip_typedefs (t);
   17558       tree decl = TYPE_NAME (t);
   17559       if (decl)
   17560 	decl = maybe_dependent_member_ref (decl, args, complain, in_decl);
   17561       if (!decl)
   17562 	return NULL_TREE;
   17563       return cp_build_qualified_type (TREE_TYPE (decl), cp_type_quals (t),
   17564 				      complain);
   17565     }
   17566 
   17567   tree name = DECL_NAME (t);
   17568   tree fullname = name;
   17569   if (instantiates_primary_template_p (t))
   17570     {
   17571       tree tinfo = get_template_info (t);
   17572       name = DECL_NAME (TI_TEMPLATE (tinfo));
   17573       tree targs = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
   17574       targs = tsubst_template_args (targs, args, complain, in_decl);
   17575       fullname = build_nt (TEMPLATE_ID_EXPR, name, targs);
   17576     }
   17577 
   17578   if (TREE_CODE (t) == TYPE_DECL)
   17579     {
   17580       if (TREE_CODE (TREE_TYPE (t)) == TYPENAME_TYPE
   17581 	  && TYPE_NAME (TREE_TYPE (t)) == t)
   17582 	/* The TYPE_DECL for a typename has DECL_CONTEXT of the typename
   17583 	   scope, but it doesn't need to be rewritten again.  */
   17584 	return NULL_TREE;
   17585       tree type = build_typename_type (ctx, name, fullname, typename_type);
   17586       return TYPE_NAME (type);
   17587     }
   17588   else if (DECL_TYPE_TEMPLATE_P (t))
   17589     return make_unbound_class_template (ctx, name,
   17590 					NULL_TREE, complain);
   17591   else
   17592     return build_qualified_name (NULL_TREE, ctx, fullname,
   17593 				 TREE_CODE (t) == TEMPLATE_DECL);
   17594 }
   17595 
   17596 /* Helper function for tsubst_omp_clauses, used for instantiation of
   17597    OMP_CLAUSE_DECL of clauses.  */
   17598 
   17599 static tree
   17600 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
   17601 			tree in_decl, tree *iterator_cache)
   17602 {
   17603   if (decl == NULL_TREE || decl == ridpointers[RID_OMP_ALL_MEMORY])
   17604     return decl;
   17605 
   17606   /* Handle OpenMP iterators.  */
   17607   if (TREE_CODE (decl) == TREE_LIST
   17608       && TREE_PURPOSE (decl)
   17609       && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
   17610     {
   17611       tree ret;
   17612       if (iterator_cache[0] == TREE_PURPOSE (decl))
   17613 	ret = iterator_cache[1];
   17614       else
   17615 	{
   17616 	  tree *tp = &ret;
   17617 	  begin_scope (sk_omp, NULL);
   17618 	  for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
   17619 	    {
   17620 	      *tp = copy_node (it);
   17621 	      TREE_VEC_ELT (*tp, 0)
   17622 		= tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
   17623 	      DECL_CONTEXT (TREE_VEC_ELT (*tp, 0)) = current_function_decl;
   17624 	      pushdecl (TREE_VEC_ELT (*tp, 0));
   17625 	      TREE_VEC_ELT (*tp, 1)
   17626 		= tsubst_stmt (TREE_VEC_ELT (it, 1), args, complain, in_decl);
   17627 	      TREE_VEC_ELT (*tp, 2)
   17628 		= tsubst_stmt (TREE_VEC_ELT (it, 2), args, complain, in_decl);
   17629 	      TREE_VEC_ELT (*tp, 3)
   17630 		= tsubst_stmt (TREE_VEC_ELT (it, 3), args, complain, in_decl);
   17631 	      TREE_CHAIN (*tp) = NULL_TREE;
   17632 	      tp = &TREE_CHAIN (*tp);
   17633 	    }
   17634 	  TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
   17635 	  iterator_cache[0] = TREE_PURPOSE (decl);
   17636 	  iterator_cache[1] = ret;
   17637 	}
   17638       return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
   17639 							   args, complain,
   17640 							   in_decl, NULL));
   17641     }
   17642 
   17643   /* Handle an OpenMP array section represented as a TREE_LIST (or
   17644      OMP_CLAUSE_DOACROSS_KIND).  An OMP_CLAUSE_DOACROSS (with a depend
   17645      kind of OMP_CLAUSE_DOACROSS_SINK) can also be represented as a
   17646      TREE_LIST.  We can handle it exactly the same as an array section
   17647      (purpose, value, and a chain), even though the nomenclature
   17648      (low_bound, length, etc) is different.  */
   17649   if (TREE_CODE (decl) == TREE_LIST)
   17650     {
   17651       tree low_bound
   17652 	= tsubst_stmt (TREE_PURPOSE (decl), args, complain, in_decl);
   17653       tree length = tsubst_stmt (TREE_VALUE (decl), args, complain, in_decl);
   17654       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
   17655 					   in_decl, NULL);
   17656       if (TREE_PURPOSE (decl) == low_bound
   17657 	  && TREE_VALUE (decl) == length
   17658 	  && TREE_CHAIN (decl) == chain)
   17659 	return decl;
   17660       tree ret = tree_cons (low_bound, length, chain);
   17661       OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (ret)
   17662 	= OMP_CLAUSE_DOACROSS_SINK_NEGATIVE (decl);
   17663       return ret;
   17664     }
   17665   else if (TREE_CODE (decl) == OMP_ARRAY_SECTION)
   17666     {
   17667       tree low_bound
   17668 	= tsubst_stmt (TREE_OPERAND (decl, 1), args, complain, in_decl);
   17669       tree length = tsubst_stmt (TREE_OPERAND (decl, 2), args, complain,
   17670 				 in_decl);
   17671       tree base = tsubst_omp_clause_decl (TREE_OPERAND (decl, 0), args,
   17672 					   complain, in_decl, NULL);
   17673       if (TREE_OPERAND (decl, 0) == base
   17674 	  && TREE_OPERAND (decl, 1) == low_bound
   17675 	  && TREE_OPERAND (decl, 2) == length)
   17676 	return decl;
   17677       return build3 (OMP_ARRAY_SECTION, TREE_TYPE (base), base, low_bound,
   17678 		     length);
   17679     }
   17680   tree ret = tsubst_stmt (decl, args, complain, in_decl);
   17681   /* Undo convert_from_reference tsubst_expr could have called.  */
   17682   if (decl
   17683       && REFERENCE_REF_P (ret)
   17684       && !REFERENCE_REF_P (decl))
   17685     ret = TREE_OPERAND (ret, 0);
   17686   return ret;
   17687 }
   17688 
   17689 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
   17690 
   17691 static tree
   17692 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
   17693 		    tree args, tsubst_flags_t complain, tree in_decl)
   17694 {
   17695   tree new_clauses = NULL_TREE, nc, oc;
   17696   tree linear_no_step = NULL_TREE;
   17697   tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
   17698 
   17699   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
   17700     {
   17701       nc = copy_node (oc);
   17702       OMP_CLAUSE_CHAIN (nc) = new_clauses;
   17703       new_clauses = nc;
   17704 
   17705       switch (OMP_CLAUSE_CODE (nc))
   17706 	{
   17707 	case OMP_CLAUSE_LASTPRIVATE:
   17708 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
   17709 	    {
   17710 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
   17711 	      tsubst_stmt (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args,
   17712 			   complain, in_decl);
   17713 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
   17714 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
   17715 	    }
   17716 	  /* FALLTHRU */
   17717 	case OMP_CLAUSE_PRIVATE:
   17718 	case OMP_CLAUSE_SHARED:
   17719 	case OMP_CLAUSE_FIRSTPRIVATE:
   17720 	case OMP_CLAUSE_COPYIN:
   17721 	case OMP_CLAUSE_COPYPRIVATE:
   17722 	case OMP_CLAUSE_UNIFORM:
   17723 	case OMP_CLAUSE_DEPEND:
   17724 	case OMP_CLAUSE_DOACROSS:
   17725 	case OMP_CLAUSE_AFFINITY:
   17726 	case OMP_CLAUSE_FROM:
   17727 	case OMP_CLAUSE_TO:
   17728 	case OMP_CLAUSE_MAP:
   17729 	case OMP_CLAUSE__CACHE_:
   17730 	case OMP_CLAUSE_NONTEMPORAL:
   17731 	case OMP_CLAUSE_USE_DEVICE_PTR:
   17732 	case OMP_CLAUSE_USE_DEVICE_ADDR:
   17733 	case OMP_CLAUSE_IS_DEVICE_PTR:
   17734 	case OMP_CLAUSE_HAS_DEVICE_ADDR:
   17735 	case OMP_CLAUSE_INCLUSIVE:
   17736 	case OMP_CLAUSE_EXCLUSIVE:
   17737 	  OMP_CLAUSE_DECL (nc)
   17738 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
   17739 				      in_decl, iterator_cache);
   17740 	  break;
   17741 	case OMP_CLAUSE_NUM_TEAMS:
   17742 	  if (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc))
   17743 	    OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (nc)
   17744 	      = tsubst_stmt (OMP_CLAUSE_NUM_TEAMS_LOWER_EXPR (oc), args,
   17745 			     complain, in_decl);
   17746 	  /* FALLTHRU */
   17747 	case OMP_CLAUSE_TILE:
   17748 	case OMP_CLAUSE_IF:
   17749 	case OMP_CLAUSE_SELF:
   17750 	case OMP_CLAUSE_NUM_THREADS:
   17751 	case OMP_CLAUSE_SCHEDULE:
   17752 	case OMP_CLAUSE_COLLAPSE:
   17753 	case OMP_CLAUSE_FINAL:
   17754 	case OMP_CLAUSE_DEVICE:
   17755 	case OMP_CLAUSE_DIST_SCHEDULE:
   17756 	case OMP_CLAUSE_THREAD_LIMIT:
   17757 	case OMP_CLAUSE_SAFELEN:
   17758 	case OMP_CLAUSE_SIMDLEN:
   17759 	case OMP_CLAUSE_NUM_TASKS:
   17760 	case OMP_CLAUSE_GRAINSIZE:
   17761 	case OMP_CLAUSE_PRIORITY:
   17762 	case OMP_CLAUSE_ORDERED:
   17763 	case OMP_CLAUSE_HINT:
   17764 	case OMP_CLAUSE_FILTER:
   17765 	case OMP_CLAUSE_NUM_GANGS:
   17766 	case OMP_CLAUSE_NUM_WORKERS:
   17767 	case OMP_CLAUSE_VECTOR_LENGTH:
   17768 	case OMP_CLAUSE_WORKER:
   17769 	case OMP_CLAUSE_VECTOR:
   17770 	case OMP_CLAUSE_ASYNC:
   17771 	case OMP_CLAUSE_WAIT:
   17772 	case OMP_CLAUSE_DETACH:
   17773 	  OMP_CLAUSE_OPERAND (nc, 0)
   17774 	    = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 0), args, complain, in_decl);
   17775 	  break;
   17776 	case OMP_CLAUSE_REDUCTION:
   17777 	case OMP_CLAUSE_IN_REDUCTION:
   17778 	case OMP_CLAUSE_TASK_REDUCTION:
   17779 	  if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
   17780 	    {
   17781 	      tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
   17782 	      if (TREE_CODE (placeholder) == SCOPE_REF)
   17783 		{
   17784 		  tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
   17785 				       complain, in_decl);
   17786 		  OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
   17787 		    = build_qualified_name (NULL_TREE, scope,
   17788 					    TREE_OPERAND (placeholder, 1),
   17789 					    false);
   17790 		}
   17791 	      else
   17792 		gcc_assert (identifier_p (placeholder));
   17793 	    }
   17794 	  OMP_CLAUSE_DECL (nc)
   17795 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
   17796 				      in_decl, NULL);
   17797 	  break;
   17798 	case OMP_CLAUSE_GANG:
   17799 	case OMP_CLAUSE_ALIGNED:
   17800 	  OMP_CLAUSE_DECL (nc)
   17801 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
   17802 				      in_decl, NULL);
   17803 	  OMP_CLAUSE_OPERAND (nc, 1)
   17804 	    = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
   17805 	  break;
   17806 	case OMP_CLAUSE_ALLOCATE:
   17807 	  OMP_CLAUSE_DECL (nc)
   17808 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
   17809 				      in_decl, NULL);
   17810 	  OMP_CLAUSE_OPERAND (nc, 1)
   17811 	    = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 1), args, complain, in_decl);
   17812 	  OMP_CLAUSE_OPERAND (nc, 2)
   17813 	    = tsubst_stmt (OMP_CLAUSE_OPERAND (oc, 2), args, complain, in_decl);
   17814 	  break;
   17815 	case OMP_CLAUSE_LINEAR:
   17816 	  OMP_CLAUSE_DECL (nc)
   17817 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
   17818 				      in_decl, NULL);
   17819 	  if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
   17820 	    {
   17821 	      gcc_assert (!linear_no_step);
   17822 	      linear_no_step = nc;
   17823 	    }
   17824 	  else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
   17825 	    OMP_CLAUSE_LINEAR_STEP (nc)
   17826 	      = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
   17827 					complain, in_decl, NULL);
   17828 	  else
   17829 	    OMP_CLAUSE_LINEAR_STEP (nc)
   17830 	      = tsubst_stmt (OMP_CLAUSE_LINEAR_STEP (oc), args,
   17831 			     complain, in_decl);
   17832 	  break;
   17833 	case OMP_CLAUSE_NOWAIT:
   17834 	case OMP_CLAUSE_DEFAULT:
   17835 	case OMP_CLAUSE_UNTIED:
   17836 	case OMP_CLAUSE_MERGEABLE:
   17837 	case OMP_CLAUSE_INBRANCH:
   17838 	case OMP_CLAUSE_NOTINBRANCH:
   17839 	case OMP_CLAUSE_PROC_BIND:
   17840 	case OMP_CLAUSE_FOR:
   17841 	case OMP_CLAUSE_PARALLEL:
   17842 	case OMP_CLAUSE_SECTIONS:
   17843 	case OMP_CLAUSE_TASKGROUP:
   17844 	case OMP_CLAUSE_NOGROUP:
   17845 	case OMP_CLAUSE_THREADS:
   17846 	case OMP_CLAUSE_SIMD:
   17847 	case OMP_CLAUSE_DEFAULTMAP:
   17848 	case OMP_CLAUSE_ORDER:
   17849 	case OMP_CLAUSE_BIND:
   17850 	case OMP_CLAUSE_INDEPENDENT:
   17851 	case OMP_CLAUSE_AUTO:
   17852 	case OMP_CLAUSE_SEQ:
   17853 	case OMP_CLAUSE_IF_PRESENT:
   17854 	case OMP_CLAUSE_FINALIZE:
   17855 	case OMP_CLAUSE_NOHOST:
   17856 	  break;
   17857 	default:
   17858 	  gcc_unreachable ();
   17859 	}
   17860       if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
   17861 	switch (OMP_CLAUSE_CODE (nc))
   17862 	  {
   17863 	  case OMP_CLAUSE_SHARED:
   17864 	  case OMP_CLAUSE_PRIVATE:
   17865 	  case OMP_CLAUSE_FIRSTPRIVATE:
   17866 	  case OMP_CLAUSE_LASTPRIVATE:
   17867 	  case OMP_CLAUSE_COPYPRIVATE:
   17868 	  case OMP_CLAUSE_LINEAR:
   17869 	  case OMP_CLAUSE_REDUCTION:
   17870 	  case OMP_CLAUSE_IN_REDUCTION:
   17871 	  case OMP_CLAUSE_TASK_REDUCTION:
   17872 	  case OMP_CLAUSE_USE_DEVICE_PTR:
   17873 	  case OMP_CLAUSE_USE_DEVICE_ADDR:
   17874 	  case OMP_CLAUSE_IS_DEVICE_PTR:
   17875 	  case OMP_CLAUSE_HAS_DEVICE_ADDR:
   17876 	  case OMP_CLAUSE_INCLUSIVE:
   17877 	  case OMP_CLAUSE_EXCLUSIVE:
   17878 	  case OMP_CLAUSE_ALLOCATE:
   17879 	    /* tsubst_expr on SCOPE_REF results in returning
   17880 	       finish_non_static_data_member result.  Undo that here.  */
   17881 	    if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
   17882 		&& (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
   17883 		    == IDENTIFIER_NODE))
   17884 	      {
   17885 		tree t = OMP_CLAUSE_DECL (nc);
   17886 		tree v = t;
   17887 		while (v)
   17888 		  switch (TREE_CODE (v))
   17889 		    {
   17890 		    case COMPONENT_REF:
   17891 		    case MEM_REF:
   17892 		    case INDIRECT_REF:
   17893 		    CASE_CONVERT:
   17894 		    case POINTER_PLUS_EXPR:
   17895 		      v = TREE_OPERAND (v, 0);
   17896 		      continue;
   17897 		    case PARM_DECL:
   17898 		      if (DECL_CONTEXT (v) == current_function_decl
   17899 			  && DECL_ARTIFICIAL (v)
   17900 			  && DECL_NAME (v) == this_identifier)
   17901 			OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
   17902 		      /* FALLTHRU */
   17903 		    default:
   17904 		      v = NULL_TREE;
   17905 		      break;
   17906 		    }
   17907 	      }
   17908 	    else if (VAR_P (OMP_CLAUSE_DECL (oc))
   17909 		     && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
   17910 		     && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
   17911 		     && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
   17912 		     && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
   17913 	      {
   17914 		tree decl = OMP_CLAUSE_DECL (nc);
   17915 		if (VAR_P (decl))
   17916 		  {
   17917 		    retrofit_lang_decl (decl);
   17918 		    DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
   17919 		  }
   17920 	      }
   17921 	    break;
   17922 	  default:
   17923 	    break;
   17924 	  }
   17925     }
   17926 
   17927   new_clauses = nreverse (new_clauses);
   17928   if (ort != C_ORT_OMP_DECLARE_SIMD)
   17929     {
   17930       new_clauses = finish_omp_clauses (new_clauses, ort);
   17931       if (linear_no_step)
   17932 	for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
   17933 	  if (nc == linear_no_step)
   17934 	    {
   17935 	      OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
   17936 	      break;
   17937 	    }
   17938     }
   17939   return new_clauses;
   17940 }
   17941 
   17942 /* Like tsubst_expr, but unshare TREE_LIST nodes.  */
   17943 
   17944 static tree
   17945 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
   17946 			  tree in_decl)
   17947 {
   17948 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
   17949 
   17950   tree purpose, value, chain;
   17951 
   17952   if (t == NULL)
   17953     return t;
   17954 
   17955   if (TREE_CODE (t) != TREE_LIST)
   17956     return tsubst_expr (t, args, complain, in_decl);
   17957 
   17958   if (t == void_list_node)
   17959     return t;
   17960 
   17961   purpose = TREE_PURPOSE (t);
   17962   if (purpose)
   17963     purpose = RECUR (purpose);
   17964   value = TREE_VALUE (t);
   17965   if (value)
   17966     {
   17967       if (TREE_CODE (value) != LABEL_DECL)
   17968 	value = RECUR (value);
   17969       else
   17970 	{
   17971 	  value = lookup_label (DECL_NAME (value));
   17972 	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
   17973 	  TREE_USED (value) = 1;
   17974 	}
   17975     }
   17976   chain = TREE_CHAIN (t);
   17977   if (chain && chain != void_type_node)
   17978     chain = RECUR (chain);
   17979   return tree_cons (purpose, value, chain);
   17980 #undef RECUR
   17981 }
   17982 
   17983 /* Used to temporarily communicate the list of #pragma omp parallel
   17984    clauses to #pragma omp for instantiation if they are combined
   17985    together.  */
   17986 
   17987 static tree *omp_parallel_combined_clauses;
   17988 
   17989 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
   17990 				 cp_decomp *);
   17991 
   17992 /* Substitute one OMP_FOR iterator.  */
   17993 
   17994 static bool
   17995 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
   17996 			 tree initv, tree condv, tree incrv, tree *clauses,
   17997 			 tree args, tsubst_flags_t complain, tree in_decl)
   17998 {
   17999 #define RECUR(NODE)				\
   18000   tsubst_stmt ((NODE), args, complain, in_decl)
   18001   tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
   18002   bool ret = false;
   18003 
   18004   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
   18005   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
   18006 
   18007   decl = TREE_OPERAND (init, 0);
   18008   init = TREE_OPERAND (init, 1);
   18009   tree decl_expr = NULL_TREE;
   18010   bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
   18011   if (range_for)
   18012     {
   18013       bool decomp = false;
   18014       if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
   18015 	{
   18016 	  tree v = DECL_VALUE_EXPR (decl);
   18017 	  if (TREE_CODE (v) == ARRAY_REF
   18018 	      && VAR_P (TREE_OPERAND (v, 0))
   18019 	      && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
   18020 	    {
   18021 	      cp_decomp decomp_d = { NULL_TREE, 0 };
   18022 	      tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
   18023 	      maybe_push_decl (d);
   18024 	      d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
   18025 				       in_decl, &decomp_d);
   18026 	      decomp = true;
   18027 	      if (d == error_mark_node)
   18028 		decl = error_mark_node;
   18029 	      else
   18030 		for (unsigned int i = 0; i < decomp_d.count; i++)
   18031 		  {
   18032 		    if (!DECL_HAS_VALUE_EXPR_P (decomp_d.decl))
   18033 		      {
   18034 			tree v = build_nt (ARRAY_REF, d,
   18035 					   size_int (decomp_d.count - i - 1),
   18036 					   NULL_TREE, NULL_TREE);
   18037 			SET_DECL_VALUE_EXPR (decomp_d.decl, v);
   18038 			DECL_HAS_VALUE_EXPR_P (decomp_d.decl) = 1;
   18039 		      }
   18040 		    fit_decomposition_lang_decl (decomp_d.decl, d);
   18041 		    decomp_d.decl = DECL_CHAIN (decomp_d.decl);
   18042 		  }
   18043 	    }
   18044 	}
   18045       decl = tsubst_decl (decl, args, complain);
   18046       if (!decomp)
   18047 	maybe_push_decl (decl);
   18048     }
   18049   else if (init && TREE_CODE (init) == DECL_EXPR)
   18050     {
   18051       /* We need to jump through some hoops to handle declarations in the
   18052 	 init-statement, since we might need to handle auto deduction,
   18053 	 but we need to keep control of initialization.  */
   18054       decl_expr = init;
   18055       init = DECL_INITIAL (DECL_EXPR_DECL (init));
   18056       decl = tsubst_decl (decl, args, complain);
   18057     }
   18058   else
   18059     {
   18060       if (TREE_CODE (decl) == SCOPE_REF)
   18061 	{
   18062 	  decl = RECUR (decl);
   18063 	  if (TREE_CODE (decl) == COMPONENT_REF)
   18064 	    {
   18065 	      tree v = decl;
   18066 	      while (v)
   18067 		switch (TREE_CODE (v))
   18068 		  {
   18069 		  case COMPONENT_REF:
   18070 		  case MEM_REF:
   18071 		  case INDIRECT_REF:
   18072 		  CASE_CONVERT:
   18073 		  case POINTER_PLUS_EXPR:
   18074 		    v = TREE_OPERAND (v, 0);
   18075 		    continue;
   18076 		  case PARM_DECL:
   18077 		    if (DECL_CONTEXT (v) == current_function_decl
   18078 			&& DECL_ARTIFICIAL (v)
   18079 			&& DECL_NAME (v) == this_identifier)
   18080 		      {
   18081 			decl = TREE_OPERAND (decl, 1);
   18082 			decl = omp_privatize_field (decl, false);
   18083 		      }
   18084 		    /* FALLTHRU */
   18085 		  default:
   18086 		    v = NULL_TREE;
   18087 		    break;
   18088 		  }
   18089 	    }
   18090 	}
   18091       else
   18092 	decl = RECUR (decl);
   18093     }
   18094   if (init && TREE_CODE (init) == TREE_VEC)
   18095     {
   18096       init = copy_node (init);
   18097       TREE_VEC_ELT (init, 0)
   18098 	= tsubst_decl (TREE_VEC_ELT (init, 0), args, complain);
   18099       TREE_VEC_ELT (init, 1) = RECUR (TREE_VEC_ELT (init, 1));
   18100       TREE_VEC_ELT (init, 2) = RECUR (TREE_VEC_ELT (init, 2));
   18101     }
   18102   else
   18103     init = RECUR (init);
   18104 
   18105   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
   18106     {
   18107       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
   18108       if (TREE_CODE (o) == TREE_LIST)
   18109 	TREE_VEC_ELT (orig_declv, i)
   18110 	  = tree_cons (RECUR (TREE_PURPOSE (o)),
   18111 		       RECUR (TREE_VALUE (o)),
   18112 		       NULL_TREE);
   18113       else
   18114 	TREE_VEC_ELT (orig_declv, i) = RECUR (o);
   18115     }
   18116 
   18117   if (range_for)
   18118     {
   18119       tree this_pre_body = NULL_TREE;
   18120       tree orig_init = NULL_TREE;
   18121       tree orig_decl = NULL_TREE;
   18122       tree init_sl = NULL_TREE;
   18123       cp_convert_omp_range_for (this_pre_body, init_sl, decl, orig_decl, init,
   18124 				orig_init, cond, incr);
   18125       if (orig_decl)
   18126 	{
   18127 	  if (orig_declv == NULL_TREE)
   18128 	    orig_declv = copy_node (declv);
   18129 	  TREE_VEC_ELT (orig_declv, i) = orig_decl;
   18130 	  ret = true;
   18131 	}
   18132       else if (orig_declv)
   18133 	TREE_VEC_ELT (orig_declv, i) = decl;
   18134     }
   18135 
   18136   tree auto_node = type_uses_auto (TREE_TYPE (decl));
   18137   if (!range_for && auto_node && init)
   18138     TREE_TYPE (decl)
   18139       = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
   18140 
   18141   gcc_assert (!type_dependent_expression_p (decl));
   18142 
   18143   if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
   18144     {
   18145       if (decl_expr)
   18146 	{
   18147 	  /* Declare the variable, but don't let that initialize it.  */
   18148 	  tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
   18149 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
   18150 	  RECUR (decl_expr);
   18151 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
   18152 	}
   18153 
   18154       if (!range_for)
   18155 	{
   18156 	  cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
   18157 	  if (COMPARISON_CLASS_P (cond)
   18158 	      && TREE_CODE (TREE_OPERAND (cond, 1)) == TREE_VEC)
   18159 	    {
   18160 	      tree lhs = RECUR (TREE_OPERAND (cond, 0));
   18161 	      tree rhs = copy_node (TREE_OPERAND (cond, 1));
   18162 	      TREE_VEC_ELT (rhs, 0)
   18163 		= tsubst_decl (TREE_VEC_ELT (rhs, 0), args, complain);
   18164 	      TREE_VEC_ELT (rhs, 1) = RECUR (TREE_VEC_ELT (rhs, 1));
   18165 	      TREE_VEC_ELT (rhs, 2) = RECUR (TREE_VEC_ELT (rhs, 2));
   18166 	      cond = build2 (TREE_CODE (cond), TREE_TYPE (cond),
   18167 			     lhs, rhs);
   18168 	    }
   18169 	  else
   18170 	    cond = RECUR (cond);
   18171 	  incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
   18172 	  if (TREE_CODE (incr) == MODIFY_EXPR)
   18173 	    {
   18174 	      tree lhs = RECUR (TREE_OPERAND (incr, 0));
   18175 	      tree rhs = RECUR (TREE_OPERAND (incr, 1));
   18176 	      incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
   18177 					  NOP_EXPR, rhs, NULL_TREE, complain);
   18178 	    }
   18179 	  else
   18180 	    incr = RECUR (incr);
   18181 	  if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
   18182 	    TREE_VEC_ELT (orig_declv, i) = decl;
   18183 	}
   18184       TREE_VEC_ELT (declv, i) = decl;
   18185       TREE_VEC_ELT (initv, i) = init;
   18186       TREE_VEC_ELT (condv, i) = cond;
   18187       TREE_VEC_ELT (incrv, i) = incr;
   18188       return ret;
   18189     }
   18190 
   18191   if (decl_expr)
   18192     {
   18193       /* Declare and initialize the variable.  */
   18194       RECUR (decl_expr);
   18195       init = NULL_TREE;
   18196     }
   18197   else if (init)
   18198     {
   18199       tree *pc;
   18200       int j;
   18201       for (j = ((omp_parallel_combined_clauses == NULL
   18202 		|| TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
   18203 	{
   18204 	  for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
   18205 	    {
   18206 	      if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
   18207 		  && OMP_CLAUSE_DECL (*pc) == decl)
   18208 		break;
   18209 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
   18210 		       && OMP_CLAUSE_DECL (*pc) == decl)
   18211 		{
   18212 		  if (j)
   18213 		    break;
   18214 		  /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
   18215 		  tree c = *pc;
   18216 		  *pc = OMP_CLAUSE_CHAIN (c);
   18217 		  OMP_CLAUSE_CHAIN (c) = *clauses;
   18218 		  *clauses = c;
   18219 		}
   18220 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
   18221 		       && OMP_CLAUSE_DECL (*pc) == decl)
   18222 		{
   18223 		  error ("iteration variable %qD should not be firstprivate",
   18224 			 decl);
   18225 		  *pc = OMP_CLAUSE_CHAIN (*pc);
   18226 		}
   18227 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
   18228 		       && OMP_CLAUSE_DECL (*pc) == decl)
   18229 		{
   18230 		  error ("iteration variable %qD should not be reduction",
   18231 			 decl);
   18232 		  *pc = OMP_CLAUSE_CHAIN (*pc);
   18233 		}
   18234 	      else
   18235 		pc = &OMP_CLAUSE_CHAIN (*pc);
   18236 	    }
   18237 	  if (*pc)
   18238 	    break;
   18239 	}
   18240       if (*pc == NULL_TREE)
   18241 	{
   18242 	  tree c = build_omp_clause (input_location,
   18243 				     TREE_CODE (t) == OMP_LOOP
   18244 				     ? OMP_CLAUSE_LASTPRIVATE
   18245 				     : OMP_CLAUSE_PRIVATE);
   18246 	  OMP_CLAUSE_DECL (c) = decl;
   18247 	  c = finish_omp_clauses (c, C_ORT_OMP);
   18248 	  if (c)
   18249 	    {
   18250 	      OMP_CLAUSE_CHAIN (c) = *clauses;
   18251 	      *clauses = c;
   18252 	    }
   18253 	}
   18254     }
   18255   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
   18256   if (COMPARISON_CLASS_P (cond))
   18257     {
   18258       tree op0 = RECUR (TREE_OPERAND (cond, 0));
   18259       tree op1 = RECUR (TREE_OPERAND (cond, 1));
   18260       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
   18261     }
   18262   else
   18263     cond = RECUR (cond);
   18264   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
   18265   switch (TREE_CODE (incr))
   18266     {
   18267     case PREINCREMENT_EXPR:
   18268     case PREDECREMENT_EXPR:
   18269     case POSTINCREMENT_EXPR:
   18270     case POSTDECREMENT_EXPR:
   18271       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
   18272 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
   18273       break;
   18274     case MODIFY_EXPR:
   18275       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
   18276 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
   18277 	{
   18278 	  tree rhs = TREE_OPERAND (incr, 1);
   18279 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
   18280 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
   18281 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
   18282 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
   18283 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
   18284 				 rhs0, rhs1));
   18285 	}
   18286       else
   18287 	incr = RECUR (incr);
   18288       break;
   18289     case MODOP_EXPR:
   18290       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
   18291 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
   18292 	{
   18293 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
   18294 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
   18295 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
   18296 				 TREE_TYPE (decl), lhs,
   18297 				 RECUR (TREE_OPERAND (incr, 2))));
   18298 	}
   18299       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
   18300 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
   18301 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
   18302 	{
   18303 	  tree rhs = TREE_OPERAND (incr, 2);
   18304 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
   18305 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
   18306 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
   18307 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
   18308 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
   18309 				 rhs0, rhs1));
   18310 	}
   18311       else
   18312 	incr = RECUR (incr);
   18313       break;
   18314     default:
   18315       incr = RECUR (incr);
   18316       break;
   18317     }
   18318 
   18319   if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
   18320     TREE_VEC_ELT (orig_declv, i) = decl;
   18321   TREE_VEC_ELT (declv, i) = decl;
   18322   TREE_VEC_ELT (initv, i) = init;
   18323   TREE_VEC_ELT (condv, i) = cond;
   18324   TREE_VEC_ELT (incrv, i) = incr;
   18325   return false;
   18326 #undef RECUR
   18327 }
   18328 
   18329 /* Helper function of tsubst_expr, find OMP_TEAMS inside
   18330    of OMP_TARGET's body.  */
   18331 
   18332 static tree
   18333 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
   18334 {
   18335   *walk_subtrees = 0;
   18336   switch (TREE_CODE (*tp))
   18337     {
   18338     case OMP_TEAMS:
   18339       return *tp;
   18340     case BIND_EXPR:
   18341     case STATEMENT_LIST:
   18342       *walk_subtrees = 1;
   18343       break;
   18344     default:
   18345       break;
   18346     }
   18347   return NULL_TREE;
   18348 }
   18349 
   18350 /* Helper function for tsubst_expr.  For decomposition declaration
   18351    artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
   18352    also the corresponding decls representing the identifiers
   18353    of the decomposition declaration.  Return DECL if successful
   18354    or error_mark_node otherwise, set *FIRST to the first decl
   18355    in the list chained through DECL_CHAIN and *CNT to the number
   18356    of such decls.  */
   18357 
   18358 static tree
   18359 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
   18360 		     tsubst_flags_t complain, tree in_decl, cp_decomp *decomp)
   18361 {
   18362   tree decl2, decl3, prev = decl;
   18363   decomp->count = 0;
   18364   gcc_assert (DECL_NAME (decl) == NULL_TREE);
   18365   for (decl2 = DECL_CHAIN (pattern_decl);
   18366        decl2
   18367        && VAR_P (decl2)
   18368        && DECL_DECOMPOSITION_P (decl2)
   18369        && DECL_NAME (decl2);
   18370        decl2 = DECL_CHAIN (decl2))
   18371     {
   18372       if (TREE_TYPE (decl2) == error_mark_node && decomp->count == 0)
   18373 	{
   18374 	  gcc_assert (errorcount);
   18375 	  return error_mark_node;
   18376 	}
   18377       decomp->count++;
   18378       gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
   18379       gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
   18380       tree v = DECL_VALUE_EXPR (decl2);
   18381       DECL_HAS_VALUE_EXPR_P (decl2) = 0;
   18382       SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
   18383       decl3 = tsubst (decl2, args, complain, in_decl);
   18384       SET_DECL_VALUE_EXPR (decl2, v);
   18385       DECL_HAS_VALUE_EXPR_P (decl2) = 1;
   18386       if (VAR_P (decl3))
   18387 	DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
   18388       else
   18389 	{
   18390 	  gcc_assert (errorcount);
   18391 	  decl = error_mark_node;
   18392 	  continue;
   18393 	}
   18394       maybe_push_decl (decl3);
   18395       if (error_operand_p (decl3))
   18396 	decl = error_mark_node;
   18397       else if (decl != error_mark_node
   18398 	       && DECL_CHAIN (decl3) != prev
   18399 	       && decl != prev)
   18400 	{
   18401 	  gcc_assert (errorcount);
   18402 	  decl = error_mark_node;
   18403 	}
   18404       else
   18405 	prev = decl3;
   18406     }
   18407   decomp->decl = prev;
   18408   return decl;
   18409 }
   18410 
   18411 /* Return the proper local_specialization for init-capture pack DECL.  */
   18412 
   18413 static tree
   18414 lookup_init_capture_pack (tree decl)
   18415 {
   18416   /* We handle normal pack captures by forwarding to the specialization of the
   18417      captured parameter.  We can't do that for pack init-captures; we need them
   18418      to have their own local_specialization.  We created the individual
   18419      VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
   18420      when we process the DECL_EXPR for the pack init-capture in the template.
   18421      So, how do we find them?  We don't know the capture proxy pack when
   18422      building the individual resulting proxies, and we don't know the
   18423      individual proxies when instantiating the pack.  What we have in common is
   18424      the FIELD_DECL.
   18425 
   18426      So...when we instantiate the FIELD_DECL, we stick the result in
   18427      local_specializations.  Then at the DECL_EXPR we look up that result, see
   18428      how many elements it has, synthesize the names, and look them up.  */
   18429 
   18430   tree cname = DECL_NAME (decl);
   18431   tree val = DECL_VALUE_EXPR (decl);
   18432   tree field = TREE_OPERAND (val, 1);
   18433   gcc_assert (TREE_CODE (field) == FIELD_DECL);
   18434   tree fpack = retrieve_local_specialization (field);
   18435   if (fpack == error_mark_node)
   18436     return error_mark_node;
   18437 
   18438   int len = 1;
   18439   tree vec = NULL_TREE;
   18440   tree r = NULL_TREE;
   18441   if (TREE_CODE (fpack) == TREE_VEC)
   18442     {
   18443       len = TREE_VEC_LENGTH (fpack);
   18444       vec = make_tree_vec (len);
   18445       r = make_node (NONTYPE_ARGUMENT_PACK);
   18446       ARGUMENT_PACK_ARGS (r) = vec;
   18447     }
   18448   for (int i = 0; i < len; ++i)
   18449     {
   18450       tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
   18451       tree elt = lookup_name (ename);
   18452       if (vec)
   18453 	TREE_VEC_ELT (vec, i) = elt;
   18454       else
   18455 	r = elt;
   18456     }
   18457   return r;
   18458 }
   18459 
   18460 /* T is an operand of a template tree being substituted.  Return whether
   18461    T is dependent such that we should suppress some warnings that would
   18462    make sense if the substituted expression were written directly, like
   18463      template <int I> bool f() { return I == 2; }
   18464    We don't want to warn when instantiating f that comparing two constants
   18465    always has the same value.
   18466 
   18467    This is a more limited concept of dependence than instantiation-dependent;
   18468    here we don't care whether substitution could fail.  */
   18469 
   18470 static bool
   18471 dependent_operand_p (tree t)
   18472 {
   18473   while (TREE_CODE (t) == IMPLICIT_CONV_EXPR)
   18474     t = TREE_OPERAND (t, 0);
   18475   ++processing_template_decl;
   18476   bool r = (potential_constant_expression (t)
   18477 	    ? value_dependent_expression_p (t)
   18478 	    : type_dependent_expression_p (t));
   18479   --processing_template_decl;
   18480   return r;
   18481 }
   18482 
   18483 /* A superset of tsubst_expr that also handles statement trees.  */
   18484 
   18485 static tree
   18486 tsubst_stmt (tree t, tree args, tsubst_flags_t complain, tree in_decl)
   18487 {
   18488 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
   18489 #define RECUR(NODE)				\
   18490   tsubst_stmt ((NODE), args, complain, in_decl)
   18491 
   18492   tree stmt, tmp;
   18493   tree r;
   18494   location_t loc;
   18495 
   18496   if (t == NULL_TREE || t == error_mark_node)
   18497     return t;
   18498 
   18499   loc = input_location;
   18500   if (location_t eloc = cp_expr_location (t))
   18501     input_location = eloc;
   18502   if (STATEMENT_CODE_P (TREE_CODE (t)))
   18503     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
   18504 
   18505   switch (TREE_CODE (t))
   18506     {
   18507     case STATEMENT_LIST:
   18508       {
   18509 	for (tree stmt : tsi_range (t))
   18510 	  RECUR (stmt);
   18511 	break;
   18512       }
   18513 
   18514     case CTOR_INITIALIZER:
   18515       finish_mem_initializers (tsubst_initializer_list
   18516 			       (TREE_OPERAND (t, 0), args));
   18517       break;
   18518 
   18519     case RETURN_EXPR:
   18520       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
   18521       break;
   18522 
   18523     case CO_RETURN_EXPR:
   18524       finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
   18525       break;
   18526 
   18527     case EXPR_STMT:
   18528       tmp = RECUR (EXPR_STMT_EXPR (t));
   18529       if (EXPR_STMT_STMT_EXPR_RESULT (t))
   18530 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
   18531       else
   18532 	finish_expr_stmt (tmp);
   18533       break;
   18534 
   18535     case USING_STMT:
   18536       finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
   18537       break;
   18538 
   18539     case PRECONDITION_STMT:
   18540     case POSTCONDITION_STMT:
   18541       gcc_unreachable ();
   18542 
   18543     case ASSERTION_STMT:
   18544       {
   18545 	r = tsubst_contract (NULL_TREE, t, args, complain, in_decl);
   18546 	if (r != error_mark_node)
   18547 	  add_stmt (r);
   18548 	RETURN (r);
   18549       }
   18550       break;
   18551 
   18552     case DECL_EXPR:
   18553       {
   18554 	tree decl, pattern_decl;
   18555 	tree init;
   18556 
   18557 	pattern_decl = decl = DECL_EXPR_DECL (t);
   18558 	if (TREE_CODE (decl) == LABEL_DECL)
   18559 	  finish_label_decl (DECL_NAME (decl));
   18560 	else if (TREE_CODE (decl) == USING_DECL)
   18561 	  {
   18562 	    tree scope = USING_DECL_SCOPE (decl);
   18563 	    if (DECL_DEPENDENT_P (decl))
   18564 	      {
   18565 		scope = tsubst (scope, args, complain, in_decl);
   18566 		if (!MAYBE_CLASS_TYPE_P (scope)
   18567 		    && TREE_CODE (scope) != ENUMERAL_TYPE)
   18568 		  {
   18569 		    if (complain & tf_error)
   18570 		      error_at (DECL_SOURCE_LOCATION (decl), "%qT is not a "
   18571 				"class, namespace, or enumeration", scope);
   18572 		    return error_mark_node;
   18573 		  }
   18574 		finish_nonmember_using_decl (scope, DECL_NAME (decl));
   18575 	      }
   18576 	    else
   18577 	      {
   18578 		/* This is a non-dependent using-decl, and we'll have
   18579 		   used the names it found during template parsing.  We do
   18580 		   not want to do the lookup again, because we might not
   18581 		   find the things we found then.  */
   18582 		gcc_checking_assert (scope == tsubst (scope, args,
   18583 						      complain, in_decl));
   18584 		/* We still need to push the bindings so that we can look up
   18585 		   this name later.  */
   18586 		push_using_decl_bindings (DECL_NAME (decl),
   18587 					  USING_DECL_DECLS (decl));
   18588 	      }
   18589 	  }
   18590 	else if (is_capture_proxy (decl)
   18591 		 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
   18592 	  {
   18593 	    /* We're in tsubst_lambda_expr, we've already inserted a new
   18594 	       capture proxy, so look it up and register it.  */
   18595 	    tree inst;
   18596 	    if (!DECL_PACK_P (decl))
   18597 	      {
   18598 		inst = lookup_name (DECL_NAME (decl), LOOK_where::BLOCK,
   18599 				    LOOK_want::HIDDEN_LAMBDA);
   18600 		gcc_assert (inst != decl && is_capture_proxy (inst));
   18601 	      }
   18602 	    else if (is_normal_capture_proxy (decl))
   18603 	      {
   18604 		inst = (retrieve_local_specialization
   18605 			(DECL_CAPTURED_VARIABLE (decl)));
   18606 		gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
   18607 			    || DECL_PACK_P (inst));
   18608 	      }
   18609 	    else
   18610 	      inst = lookup_init_capture_pack (decl);
   18611 
   18612 	    register_local_specialization (inst, decl);
   18613 	    break;
   18614 	  }
   18615 	else if (DECL_PRETTY_FUNCTION_P (decl))
   18616 	  decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
   18617 				  DECL_NAME (decl),
   18618 				  true/*DECL_PRETTY_FUNCTION_P (decl)*/);
   18619 	else if (DECL_IMPLICIT_TYPEDEF_P (decl)
   18620 		 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
   18621 	  /* Don't copy the old closure; we'll create a new one in
   18622 	     tsubst_lambda_expr.  */
   18623 	  break;
   18624 	else
   18625 	  {
   18626 	    init = DECL_INITIAL (decl);
   18627 	    decl = tsubst (decl, args, complain, in_decl);
   18628 	    if (decl != error_mark_node)
   18629 	      {
   18630 		/* By marking the declaration as instantiated, we avoid
   18631 		   trying to instantiate it.  Since instantiate_decl can't
   18632 		   handle local variables, and since we've already done
   18633 		   all that needs to be done, that's the right thing to
   18634 		   do.  */
   18635 		if (VAR_P (decl))
   18636 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
   18637 		if (VAR_P (decl) && !DECL_NAME (decl)
   18638 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
   18639 		  /* Anonymous aggregates are a special case.  */
   18640 		  finish_anon_union (decl);
   18641 		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
   18642 		  {
   18643 		    DECL_CONTEXT (decl) = current_function_decl;
   18644 		    if (DECL_NAME (decl) == this_identifier)
   18645 		      {
   18646 			tree lam = DECL_CONTEXT (current_function_decl);
   18647 			lam = CLASSTYPE_LAMBDA_EXPR (lam);
   18648 			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
   18649 		      }
   18650 		    insert_capture_proxy (decl);
   18651 		  }
   18652 		else if (DECL_IMPLICIT_TYPEDEF_P (t))
   18653 		  /* We already did a pushtag.  */;
   18654 		else if (VAR_OR_FUNCTION_DECL_P (decl)
   18655 			 && DECL_LOCAL_DECL_P (decl))
   18656 		  {
   18657 		    if (TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
   18658 		      DECL_CONTEXT (decl) = NULL_TREE;
   18659 		    decl = pushdecl (decl);
   18660 		    if (TREE_CODE (decl) == FUNCTION_DECL
   18661 			&& DECL_OMP_DECLARE_REDUCTION_P (decl)
   18662 			&& cp_check_omp_declare_reduction (decl))
   18663 		      instantiate_body (pattern_decl, args, decl, true);
   18664 		  }
   18665 		else
   18666 		  {
   18667 		    bool const_init = false;
   18668 		    cp_decomp decomp_d, *decomp = NULL;
   18669 		    tree ndecl = error_mark_node;
   18670 		    tree asmspec_tree = NULL_TREE;
   18671 		    maybe_push_decl (decl);
   18672 
   18673 		    if (VAR_P (decl)
   18674 			&& DECL_LANG_SPECIFIC (decl)
   18675 			&& DECL_OMP_PRIVATIZED_MEMBER (decl))
   18676 		      break;
   18677 
   18678 		    if (VAR_P (decl)
   18679 			&& DECL_DECOMPOSITION_P (decl)
   18680 			&& TREE_TYPE (pattern_decl) != error_mark_node)
   18681 		      {
   18682 			decomp = &decomp_d;
   18683 			ndecl = tsubst_decomp_names (decl, pattern_decl, args,
   18684 						     complain, in_decl, decomp);
   18685 		      }
   18686 
   18687 		    init = tsubst_init (init, decl, args, complain, in_decl);
   18688 
   18689 		    if (VAR_P (decl))
   18690 		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
   18691 				    (pattern_decl));
   18692 
   18693 		    /* In a non-template function, VLA type declarations are
   18694 		       handled in grokdeclarator; for templates, handle them
   18695 		       now.  */
   18696 		    predeclare_vla (decl);
   18697 
   18698 		    if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
   18699 		      {
   18700 			tree id = DECL_ASSEMBLER_NAME (pattern_decl);
   18701 			const char *asmspec = IDENTIFIER_POINTER (id);
   18702 			gcc_assert (asmspec[0] == '*');
   18703 			asmspec_tree
   18704 			  = build_string (IDENTIFIER_LENGTH (id) - 1,
   18705 					  asmspec + 1);
   18706 			TREE_TYPE (asmspec_tree) = char_array_type_node;
   18707 		      }
   18708 
   18709 		    cp_finish_decl (decl, init, const_init, asmspec_tree, 0,
   18710 				    decomp);
   18711 
   18712 		    if (ndecl != error_mark_node)
   18713 		      cp_finish_decomp (ndecl, decomp);
   18714 		  }
   18715 	      }
   18716 	  }
   18717 
   18718 	break;
   18719       }
   18720 
   18721     case FOR_STMT:
   18722       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
   18723       RECUR (FOR_INIT_STMT (t));
   18724       finish_init_stmt (stmt);
   18725       tmp = RECUR (FOR_COND (t));
   18726       finish_for_cond (tmp, stmt, false, 0, false);
   18727       tmp = RECUR (FOR_EXPR (t));
   18728       finish_for_expr (tmp, stmt);
   18729       {
   18730 	bool prev = note_iteration_stmt_body_start ();
   18731 	RECUR (FOR_BODY (t));
   18732 	note_iteration_stmt_body_end (prev);
   18733       }
   18734       finish_for_stmt (stmt);
   18735       break;
   18736 
   18737     case RANGE_FOR_STMT:
   18738       {
   18739 	/* Construct another range_for, if this is not a final
   18740 	   substitution (for inside a generic lambda of a
   18741 	   template).  Otherwise convert to a regular for.  */
   18742         tree decl, expr;
   18743         stmt = (processing_template_decl
   18744 		? begin_range_for_stmt (NULL_TREE, NULL_TREE)
   18745 		: begin_for_stmt (NULL_TREE, NULL_TREE));
   18746 	RECUR (RANGE_FOR_INIT_STMT (t));
   18747         decl = RANGE_FOR_DECL (t);
   18748         decl = tsubst (decl, args, complain, in_decl);
   18749         maybe_push_decl (decl);
   18750         expr = RECUR (RANGE_FOR_EXPR (t));
   18751 
   18752 	cp_decomp decomp_d, *decomp = NULL;
   18753 	if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
   18754 	  {
   18755 	    decomp = &decomp_d;
   18756 	    decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
   18757 					complain, in_decl, decomp);
   18758 	  }
   18759 
   18760 	tree unroll = RECUR (RANGE_FOR_UNROLL (t));
   18761 	if (unroll)
   18762 	  unroll
   18763 	    = cp_check_pragma_unroll (EXPR_LOCATION (RANGE_FOR_UNROLL (t)),
   18764 				      unroll);
   18765 	if (processing_template_decl)
   18766 	  {
   18767 	    RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
   18768 	    RANGE_FOR_UNROLL (stmt) = unroll;
   18769 	    RANGE_FOR_NOVECTOR (stmt) = RANGE_FOR_NOVECTOR (t);
   18770 	    finish_range_for_decl (stmt, decl, expr);
   18771 	    if (decomp && decl != error_mark_node)
   18772 	      cp_finish_decomp (decl, decomp);
   18773 	  }
   18774 	else
   18775 	  stmt = cp_convert_range_for (stmt, decl, expr, decomp,
   18776 				       RANGE_FOR_IVDEP (t), unroll,
   18777 				       RANGE_FOR_NOVECTOR (t));
   18778 
   18779 	bool prev = note_iteration_stmt_body_start ();
   18780         RECUR (RANGE_FOR_BODY (t));
   18781 	note_iteration_stmt_body_end (prev);
   18782         finish_for_stmt (stmt);
   18783       }
   18784       break;
   18785 
   18786     case WHILE_STMT:
   18787       stmt = begin_while_stmt ();
   18788       tmp = RECUR (WHILE_COND (t));
   18789       finish_while_stmt_cond (tmp, stmt, false, 0, false);
   18790       {
   18791 	bool prev = note_iteration_stmt_body_start ();
   18792 	RECUR (WHILE_BODY (t));
   18793 	note_iteration_stmt_body_end (prev);
   18794       }
   18795       finish_while_stmt (stmt);
   18796       break;
   18797 
   18798     case DO_STMT:
   18799       stmt = begin_do_stmt ();
   18800       {
   18801 	bool prev = note_iteration_stmt_body_start ();
   18802 	RECUR (DO_BODY (t));
   18803 	note_iteration_stmt_body_end (prev);
   18804       }
   18805       finish_do_body (stmt);
   18806       tmp = RECUR (DO_COND (t));
   18807       finish_do_stmt (tmp, stmt, false, 0, false);
   18808       break;
   18809 
   18810     case IF_STMT:
   18811       stmt = begin_if_stmt ();
   18812       IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
   18813       IF_STMT_CONSTEVAL_P (stmt) = IF_STMT_CONSTEVAL_P (t);
   18814       if (IF_STMT_CONSTEXPR_P (t))
   18815 	args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args, complain, in_decl);
   18816       {
   18817 	tree cond = IF_COND (t);
   18818 	bool was_dep = dependent_operand_p (cond);
   18819 	cond = RECUR (cond);
   18820 	warning_sentinel s1(warn_address, was_dep);
   18821 	tmp = finish_if_stmt_cond (cond, stmt);
   18822       }
   18823       if (IF_STMT_CONSTEXPR_P (t)
   18824 	  && instantiation_dependent_expression_p (tmp))
   18825 	{
   18826 	  /* We're partially instantiating a generic lambda, but the condition
   18827 	     of the constexpr if is still dependent.  Don't substitute into the
   18828 	     branches now, just remember the template arguments.  */
   18829 	  do_poplevel (IF_SCOPE (stmt));
   18830 	  IF_SCOPE (stmt) = NULL_TREE;
   18831 	  IF_COND (stmt) = IF_COND (t);
   18832 	  THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
   18833 	  ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
   18834 	  IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (stmt, args, complain);
   18835 	  add_stmt (stmt);
   18836 	  break;
   18837 	}
   18838       if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
   18839 	/* Don't instantiate the THEN_CLAUSE. */;
   18840       else if (IF_STMT_CONSTEVAL_P (t))
   18841 	{
   18842 	  bool save_in_consteval_if_p = in_consteval_if_p;
   18843 	  in_consteval_if_p = true;
   18844 	  RECUR (THEN_CLAUSE (t));
   18845 	  in_consteval_if_p = save_in_consteval_if_p;
   18846 	}
   18847       else
   18848 	{
   18849 	  tree folded = fold_non_dependent_expr (tmp, complain);
   18850 	  bool inhibit = integer_zerop (folded);
   18851 	  if (inhibit)
   18852 	    ++c_inhibit_evaluation_warnings;
   18853 	  RECUR (THEN_CLAUSE (t));
   18854 	  if (inhibit)
   18855 	    --c_inhibit_evaluation_warnings;
   18856 	}
   18857       finish_then_clause (stmt);
   18858 
   18859       if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
   18860 	/* Don't instantiate the ELSE_CLAUSE. */;
   18861       else if (ELSE_CLAUSE (t))
   18862 	{
   18863 	  tree folded = fold_non_dependent_expr (tmp, complain);
   18864 	  bool inhibit = integer_nonzerop (folded);
   18865 	  begin_else_clause (stmt);
   18866 	  if (inhibit)
   18867 	    ++c_inhibit_evaluation_warnings;
   18868 	  RECUR (ELSE_CLAUSE (t));
   18869 	  if (inhibit)
   18870 	    --c_inhibit_evaluation_warnings;
   18871 	  finish_else_clause (stmt);
   18872 	}
   18873 
   18874       finish_if_stmt (stmt);
   18875       break;
   18876 
   18877     case BIND_EXPR:
   18878       if (BIND_EXPR_BODY_BLOCK (t))
   18879 	stmt = begin_function_body ();
   18880       else
   18881 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
   18882 				    ? BCS_TRY_BLOCK : 0);
   18883 
   18884       RECUR (BIND_EXPR_BODY (t));
   18885 
   18886       if (BIND_EXPR_BODY_BLOCK (t))
   18887 	finish_function_body (stmt);
   18888       else
   18889 	finish_compound_stmt (stmt);
   18890       break;
   18891 
   18892     case BREAK_STMT:
   18893       finish_break_stmt ();
   18894       break;
   18895 
   18896     case CONTINUE_STMT:
   18897       finish_continue_stmt ();
   18898       break;
   18899 
   18900     case SWITCH_STMT:
   18901       stmt = begin_switch_stmt ();
   18902       tmp = RECUR (SWITCH_STMT_COND (t));
   18903       finish_switch_cond (tmp, stmt);
   18904       RECUR (SWITCH_STMT_BODY (t));
   18905       finish_switch_stmt (stmt);
   18906       break;
   18907 
   18908     case CASE_LABEL_EXPR:
   18909       {
   18910 	tree decl = CASE_LABEL (t);
   18911 	tree low = RECUR (CASE_LOW (t));
   18912 	tree high = RECUR (CASE_HIGH (t));
   18913 	tree l = finish_case_label (EXPR_LOCATION (t), low, high);
   18914 	if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
   18915 	  {
   18916 	    tree label = CASE_LABEL (l);
   18917 	    FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
   18918 	    if (DECL_ATTRIBUTES (decl) != NULL_TREE)
   18919 	      cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
   18920 	  }
   18921       }
   18922       break;
   18923 
   18924     case LABEL_EXPR:
   18925       {
   18926 	tree decl = LABEL_EXPR_LABEL (t);
   18927 	tree label;
   18928 
   18929 	label = finish_label_stmt (DECL_NAME (decl));
   18930 	if (TREE_CODE (label) == LABEL_DECL)
   18931 	  FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
   18932 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
   18933 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
   18934       }
   18935       break;
   18936 
   18937     case GOTO_EXPR:
   18938       tmp = GOTO_DESTINATION (t);
   18939       if (TREE_CODE (tmp) != LABEL_DECL)
   18940 	/* Computed goto's must be tsubst'd into.  On the other hand,
   18941 	   non-computed gotos must not be; the identifier in question
   18942 	   will have no binding.  */
   18943 	tmp = RECUR (tmp);
   18944       else
   18945 	tmp = DECL_NAME (tmp);
   18946       finish_goto_stmt (tmp);
   18947       break;
   18948 
   18949     case ASM_EXPR:
   18950       {
   18951 	tree string = RECUR (ASM_STRING (t));
   18952 	tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
   18953 						 complain, in_decl);
   18954 	tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
   18955 						complain, in_decl);
   18956 	tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
   18957 	 					  complain, in_decl);
   18958 	tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
   18959 						complain, in_decl);
   18960 	tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
   18961 			       outputs, inputs, clobbers, labels,
   18962 			       ASM_INLINE_P (t));
   18963 	tree asm_expr = tmp;
   18964 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
   18965 	  asm_expr = TREE_OPERAND (asm_expr, 0);
   18966 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
   18967       }
   18968       break;
   18969 
   18970     case TRY_BLOCK:
   18971       if (CLEANUP_P (t))
   18972 	{
   18973 	  stmt = begin_try_block ();
   18974 	  RECUR (TRY_STMTS (t));
   18975 	  finish_cleanup_try_block (stmt);
   18976 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
   18977 	}
   18978       else
   18979 	{
   18980 	  tree compound_stmt = NULL_TREE;
   18981 
   18982 	  if (FN_TRY_BLOCK_P (t))
   18983 	    stmt = begin_function_try_block (&compound_stmt);
   18984 	  else
   18985 	    stmt = begin_try_block ();
   18986 
   18987 	  RECUR (TRY_STMTS (t));
   18988 
   18989 	  if (FN_TRY_BLOCK_P (t))
   18990 	    finish_function_try_block (stmt);
   18991 	  else
   18992 	    finish_try_block (stmt);
   18993 
   18994 	  RECUR (TRY_HANDLERS (t));
   18995 	  if (FN_TRY_BLOCK_P (t))
   18996 	    finish_function_handler_sequence (stmt, compound_stmt);
   18997 	  else
   18998 	    finish_handler_sequence (stmt);
   18999 	}
   19000       break;
   19001 
   19002     case HANDLER:
   19003       {
   19004 	tree decl = HANDLER_PARMS (t);
   19005 
   19006 	if (decl)
   19007 	  {
   19008 	    decl = tsubst (decl, args, complain, in_decl);
   19009 	    /* Prevent instantiate_decl from trying to instantiate
   19010 	       this variable.  We've already done all that needs to be
   19011 	       done.  */
   19012 	    if (decl != error_mark_node)
   19013 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
   19014 	  }
   19015 	stmt = begin_handler ();
   19016 	finish_handler_parms (decl, stmt);
   19017 	RECUR (HANDLER_BODY (t));
   19018 	finish_handler (stmt);
   19019       }
   19020       break;
   19021 
   19022     case TAG_DEFN:
   19023       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
   19024       if (dependent_type_p (tmp))
   19025 	/* This is a partial instantiation, try again when full.  */
   19026 	add_stmt (build_min (TAG_DEFN, tmp));
   19027       else if (CLASS_TYPE_P (tmp))
   19028 	{
   19029 	  /* Local classes are not independent templates; they are
   19030 	     instantiated along with their containing function.  And this
   19031 	     way we don't have to deal with pushing out of one local class
   19032 	     to instantiate a member of another local class.  */
   19033 	  /* Closures are handled by the LAMBDA_EXPR.  */
   19034 	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
   19035 	  complete_type (tmp);
   19036 	  tree save_ccp = current_class_ptr;
   19037 	  tree save_ccr = current_class_ref;
   19038 	  for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
   19039 	    if ((VAR_P (fld)
   19040 		 || (TREE_CODE (fld) == FUNCTION_DECL
   19041 		     && !DECL_ARTIFICIAL (fld)))
   19042 		&& DECL_TEMPLATE_INSTANTIATION (fld))
   19043 	      instantiate_decl (fld, /*defer_ok=*/false,
   19044 				/*expl_inst_class=*/false);
   19045 	    else if (TREE_CODE (fld) == FIELD_DECL)
   19046 	      maybe_instantiate_nsdmi_init (fld, tf_warning_or_error);
   19047 	  current_class_ptr = save_ccp;
   19048 	  current_class_ref = save_ccr;
   19049 	}
   19050       break;
   19051 
   19052     case STATIC_ASSERT:
   19053       {
   19054 	tree condition, message;
   19055 
   19056 	++c_inhibit_evaluation_warnings;
   19057 	condition = tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
   19058 				 complain, in_decl);
   19059 	message = tsubst_expr (STATIC_ASSERT_MESSAGE (t), args,
   19060 			       complain, in_decl);
   19061 	if (TREE_CODE (STATIC_ASSERT_MESSAGE (t)) != STRING_CST
   19062 	    && TREE_CODE (message) == STRING_CST)
   19063 	  message = build1_loc (STATIC_ASSERT_SOURCE_LOCATION (t),
   19064 				PAREN_EXPR, TREE_TYPE (message), message);
   19065 	--c_inhibit_evaluation_warnings;
   19066 
   19067 	finish_static_assert (condition, message,
   19068                               STATIC_ASSERT_SOURCE_LOCATION (t),
   19069 			      /*member_p=*/false, /*show_expr_p=*/true);
   19070       }
   19071       break;
   19072 
   19073     case OACC_KERNELS:
   19074     case OACC_PARALLEL:
   19075     case OACC_SERIAL:
   19076       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC_TARGET, args,
   19077 				complain, in_decl);
   19078       stmt = begin_omp_parallel ();
   19079       RECUR (OMP_BODY (t));
   19080       finish_omp_construct (TREE_CODE (t), stmt, tmp);
   19081       break;
   19082 
   19083     case OMP_PARALLEL:
   19084       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
   19085       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
   19086 				complain, in_decl);
   19087       if (OMP_PARALLEL_COMBINED (t))
   19088 	omp_parallel_combined_clauses = &tmp;
   19089       stmt = begin_omp_parallel ();
   19090       RECUR (OMP_PARALLEL_BODY (t));
   19091       gcc_assert (omp_parallel_combined_clauses == NULL);
   19092       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
   19093 	= OMP_PARALLEL_COMBINED (t);
   19094       pop_omp_privatization_clauses (r);
   19095       break;
   19096 
   19097     case OMP_TASK:
   19098       if (OMP_TASK_BODY (t) == NULL_TREE)
   19099 	{
   19100 	  tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
   19101 				    complain, in_decl);
   19102 	  t = copy_node (t);
   19103 	  OMP_TASK_CLAUSES (t) = tmp;
   19104 	  add_stmt (t);
   19105 	  break;
   19106 	}
   19107       r = push_omp_privatization_clauses (false);
   19108       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
   19109 				complain, in_decl);
   19110       stmt = begin_omp_task ();
   19111       RECUR (OMP_TASK_BODY (t));
   19112       finish_omp_task (tmp, stmt);
   19113       pop_omp_privatization_clauses (r);
   19114       break;
   19115 
   19116     case OMP_FOR:
   19117     case OMP_LOOP:
   19118     case OMP_SIMD:
   19119     case OMP_DISTRIBUTE:
   19120     case OMP_TASKLOOP:
   19121     case OACC_LOOP:
   19122       {
   19123 	tree clauses, body, pre_body;
   19124 	tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
   19125 	tree orig_declv = NULL_TREE;
   19126 	tree incrv = NULL_TREE;
   19127 	enum c_omp_region_type ort = C_ORT_OMP;
   19128 	bool any_range_for = false;
   19129 	int i;
   19130 
   19131 	if (TREE_CODE (t) == OACC_LOOP)
   19132 	  ort = C_ORT_ACC;
   19133 
   19134 	r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
   19135 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
   19136 				      in_decl);
   19137 	if (OMP_FOR_INIT (t) != NULL_TREE)
   19138 	  {
   19139 	    declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
   19140 	    if (OMP_FOR_ORIG_DECLS (t))
   19141 	      orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
   19142 	    initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
   19143 	    condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
   19144 	    incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
   19145 	  }
   19146 
   19147 	keep_next_level (true);
   19148 	stmt = begin_omp_structured_block ();
   19149 
   19150 	pre_body = push_stmt_list ();
   19151 	RECUR (OMP_FOR_PRE_BODY (t));
   19152 	pre_body = pop_stmt_list (pre_body);
   19153 
   19154 	if (OMP_FOR_INIT (t) != NULL_TREE)
   19155 	  for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
   19156 	    any_range_for
   19157 	      |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
   19158 					  condv, incrv, &clauses, args,
   19159 					  complain, in_decl);
   19160 	omp_parallel_combined_clauses = NULL;
   19161 
   19162 	if (any_range_for)
   19163 	  {
   19164 	    gcc_assert (orig_declv);
   19165 	    body = begin_omp_structured_block ();
   19166 	    for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
   19167 	      if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
   19168 		  && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
   19169 		  && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
   19170 		cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
   19171 					 TREE_VEC_ELT (declv, i));
   19172 	  }
   19173 	else
   19174 	  body = push_stmt_list ();
   19175 	RECUR (OMP_FOR_BODY (t));
   19176 	if (any_range_for)
   19177 	  body = finish_omp_structured_block (body);
   19178 	else
   19179 	  body = pop_stmt_list (body);
   19180 
   19181 	if (OMP_FOR_INIT (t) != NULL_TREE)
   19182 	  t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
   19183 			      orig_declv, initv, condv, incrv, body, pre_body,
   19184 			      NULL, clauses);
   19185 	else
   19186 	  {
   19187 	    t = make_node (TREE_CODE (t));
   19188 	    TREE_TYPE (t) = void_type_node;
   19189 	    OMP_FOR_BODY (t) = body;
   19190 	    OMP_FOR_PRE_BODY (t) = pre_body;
   19191 	    OMP_FOR_CLAUSES (t) = clauses;
   19192 	    SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
   19193 	    add_stmt (t);
   19194 	  }
   19195 
   19196 	add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
   19197 					t));
   19198 	pop_omp_privatization_clauses (r);
   19199       }
   19200       break;
   19201 
   19202     case OMP_SECTIONS:
   19203     case OMP_MASKED:
   19204       omp_parallel_combined_clauses = NULL;
   19205       /* FALLTHRU */
   19206     case OMP_SINGLE:
   19207     case OMP_SCOPE:
   19208     case OMP_TEAMS:
   19209     case OMP_CRITICAL:
   19210     case OMP_TASKGROUP:
   19211     case OMP_SCAN:
   19212       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
   19213 					  && OMP_TEAMS_COMBINED (t));
   19214       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
   19215 				in_decl);
   19216       if (TREE_CODE (t) == OMP_TEAMS)
   19217 	{
   19218 	  keep_next_level (true);
   19219 	  stmt = begin_omp_structured_block ();
   19220 	  RECUR (OMP_BODY (t));
   19221 	  stmt = finish_omp_structured_block (stmt);
   19222 	}
   19223       else
   19224 	{
   19225 	  stmt = push_stmt_list ();
   19226 	  RECUR (OMP_BODY (t));
   19227 	  stmt = pop_stmt_list (stmt);
   19228 	}
   19229 
   19230       if (TREE_CODE (t) == OMP_CRITICAL
   19231 	  && tmp != NULL_TREE
   19232 	  && integer_nonzerop (OMP_CLAUSE_HINT_EXPR (tmp)))
   19233 	{
   19234 	  error_at (OMP_CLAUSE_LOCATION (tmp),
   19235 		    "%<#pragma omp critical%> with %<hint%> clause requires "
   19236 		    "a name, except when %<omp_sync_hint_none%> is used");
   19237 	  RETURN (error_mark_node);
   19238 	}
   19239       t = copy_node (t);
   19240       OMP_BODY (t) = stmt;
   19241       OMP_CLAUSES (t) = tmp;
   19242       add_stmt (t);
   19243       pop_omp_privatization_clauses (r);
   19244       break;
   19245 
   19246     case OMP_DEPOBJ:
   19247       r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
   19248       if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
   19249 	{
   19250 	  enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_INVALID;
   19251 	  if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
   19252 	    {
   19253 	      tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
   19254 					args, complain, in_decl);
   19255 	      if (tmp == NULL_TREE)
   19256 		tmp = error_mark_node;
   19257 	    }
   19258 	  else
   19259 	    {
   19260 	      kind = (enum omp_clause_depend_kind)
   19261 		     tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
   19262 	      tmp = NULL_TREE;
   19263 	    }
   19264 	  finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
   19265 	}
   19266       else
   19267 	finish_omp_depobj (EXPR_LOCATION (t), r,
   19268 			   OMP_CLAUSE_DEPEND_INVALID,
   19269 			   OMP_DEPOBJ_CLAUSES (t));
   19270       break;
   19271 
   19272     case OACC_DATA:
   19273     case OMP_TARGET_DATA:
   19274     case OMP_TARGET:
   19275       tmp = tsubst_omp_clauses (OMP_CLAUSES (t),
   19276 				TREE_CODE (t) == OACC_DATA
   19277 				? C_ORT_ACC
   19278 				: TREE_CODE (t) == OMP_TARGET
   19279 				? C_ORT_OMP_TARGET : C_ORT_OMP,
   19280 				args, complain, in_decl);
   19281       keep_next_level (true);
   19282       stmt = begin_omp_structured_block ();
   19283 
   19284       RECUR (OMP_BODY (t));
   19285       stmt = finish_omp_structured_block (stmt);
   19286 
   19287       t = copy_node (t);
   19288       OMP_BODY (t) = stmt;
   19289       OMP_CLAUSES (t) = tmp;
   19290 
   19291       if (TREE_CODE (t) == OMP_TARGET)
   19292 	finish_omp_target_clauses (EXPR_LOCATION (t), OMP_BODY (t),
   19293 				   &OMP_CLAUSES (t));
   19294 
   19295       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
   19296 	{
   19297 	  tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
   19298 	  if (teams)
   19299 	    /* For combined target teams, ensure the num_teams and
   19300 	       thread_limit clause expressions are evaluated on the host,
   19301 	       before entering the target construct.  */
   19302 	    for (tree c = OMP_TEAMS_CLAUSES (teams);
   19303 		 c; c = OMP_CLAUSE_CHAIN (c))
   19304 	      if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
   19305 		  || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
   19306 		for (int i = 0;
   19307 		     i <= (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS); ++i)
   19308 		  if (OMP_CLAUSE_OPERAND (c, i)
   19309 		      && TREE_CODE (OMP_CLAUSE_OPERAND (c, i)) != INTEGER_CST)
   19310 		    {
   19311 		      tree expr = OMP_CLAUSE_OPERAND (c, i);
   19312 		      expr = force_target_expr (TREE_TYPE (expr), expr,
   19313 						tf_none);
   19314 		      if (expr == error_mark_node)
   19315 			continue;
   19316 		      tmp = TARGET_EXPR_SLOT (expr);
   19317 		      add_stmt (expr);
   19318 		      OMP_CLAUSE_OPERAND (c, i) = expr;
   19319 		      tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
   19320 						  OMP_CLAUSE_FIRSTPRIVATE);
   19321 		      OMP_CLAUSE_DECL (tc) = tmp;
   19322 		      OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
   19323 		      OMP_TARGET_CLAUSES (t) = tc;
   19324 		    }
   19325 	}
   19326       add_stmt (t);
   19327       break;
   19328 
   19329     case OACC_DECLARE:
   19330       t = copy_node (t);
   19331       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
   19332 				complain, in_decl);
   19333       OACC_DECLARE_CLAUSES (t) = tmp;
   19334       add_stmt (t);
   19335       break;
   19336 
   19337     case OMP_TARGET_UPDATE:
   19338     case OMP_TARGET_ENTER_DATA:
   19339     case OMP_TARGET_EXIT_DATA:
   19340       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
   19341 				complain, in_decl);
   19342       t = copy_node (t);
   19343       OMP_STANDALONE_CLAUSES (t) = tmp;
   19344       add_stmt (t);
   19345       break;
   19346 
   19347     case OACC_CACHE:
   19348     case OACC_ENTER_DATA:
   19349     case OACC_EXIT_DATA:
   19350     case OACC_UPDATE:
   19351       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
   19352 				complain, in_decl);
   19353       t = copy_node (t);
   19354       OMP_STANDALONE_CLAUSES (t) = tmp;
   19355       add_stmt (t);
   19356       break;
   19357 
   19358     case OMP_ORDERED:
   19359       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
   19360 				complain, in_decl);
   19361       if (OMP_BODY (t))
   19362 	{
   19363 	  stmt = push_stmt_list ();
   19364 	  RECUR (OMP_BODY (t));
   19365 	  stmt = pop_stmt_list (stmt);
   19366 	}
   19367       else
   19368 	stmt = NULL_TREE;
   19369 
   19370       t = copy_node (t);
   19371       OMP_BODY (t) = stmt;
   19372       OMP_ORDERED_CLAUSES (t) = tmp;
   19373       add_stmt (t);
   19374       break;
   19375 
   19376     case OMP_MASTER:
   19377     case OMP_STRUCTURED_BLOCK:
   19378       omp_parallel_combined_clauses = NULL;
   19379       /* FALLTHRU */
   19380     case OMP_SECTION:
   19381       stmt = push_stmt_list ();
   19382       RECUR (OMP_BODY (t));
   19383       stmt = pop_stmt_list (stmt);
   19384 
   19385       t = copy_node (t);
   19386       OMP_BODY (t) = stmt;
   19387       add_stmt (t);
   19388       break;
   19389 
   19390     case OMP_ATOMIC:
   19391       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
   19392       tmp = NULL_TREE;
   19393       if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
   19394 	tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
   19395 				  complain, in_decl);
   19396       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
   19397 	{
   19398 	  tree op1 = TREE_OPERAND (t, 1);
   19399 	  tree rhs1 = NULL_TREE;
   19400 	  tree r = NULL_TREE;
   19401 	  tree lhs, rhs;
   19402 	  if (TREE_CODE (op1) == COMPOUND_EXPR)
   19403 	    {
   19404 	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
   19405 	      op1 = TREE_OPERAND (op1, 1);
   19406 	    }
   19407 	  if (TREE_CODE (op1) == COND_EXPR)
   19408 	    {
   19409 	      gcc_assert (rhs1 == NULL_TREE);
   19410 	      tree c = TREE_OPERAND (op1, 0);
   19411 	      if (TREE_CODE (c) == MODIFY_EXPR)
   19412 		{
   19413 		  r = RECUR (TREE_OPERAND (c, 0));
   19414 		  c = TREE_OPERAND (c, 1);
   19415 		}
   19416 	      gcc_assert (TREE_CODE (c) == EQ_EXPR);
   19417 	      rhs = RECUR (TREE_OPERAND (c, 1));
   19418 	      lhs = RECUR (TREE_OPERAND (op1, 2));
   19419 	      rhs1 = RECUR (TREE_OPERAND (op1, 1));
   19420 	    }
   19421 	  else
   19422 	    {
   19423 	      lhs = RECUR (TREE_OPERAND (op1, 0));
   19424 	      rhs = RECUR (TREE_OPERAND (op1, 1));
   19425 	    }
   19426 	  finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
   19427 			     lhs, rhs, NULL_TREE, NULL_TREE, rhs1, r,
   19428 			     tmp, OMP_ATOMIC_MEMORY_ORDER (t),
   19429 			     OMP_ATOMIC_WEAK (t));
   19430 	}
   19431       else
   19432 	{
   19433 	  tree op1 = TREE_OPERAND (t, 1);
   19434 	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
   19435 	  tree rhs1 = NULL_TREE, r = NULL_TREE;
   19436 	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
   19437 	  enum tree_code opcode = NOP_EXPR;
   19438 	  if (code == OMP_ATOMIC_READ)
   19439 	    {
   19440 	      v = RECUR (TREE_OPERAND (op1, 0));
   19441 	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
   19442 	    }
   19443 	  else if (code == OMP_ATOMIC_CAPTURE_OLD
   19444 		   || code == OMP_ATOMIC_CAPTURE_NEW)
   19445 	    {
   19446 	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
   19447 	      v = RECUR (TREE_OPERAND (op1, 0));
   19448 	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
   19449 	      if (TREE_CODE (op11) == COMPOUND_EXPR)
   19450 		{
   19451 		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
   19452 		  op11 = TREE_OPERAND (op11, 1);
   19453 		}
   19454 	      if (TREE_CODE (op11) == COND_EXPR)
   19455 		{
   19456 		  gcc_assert (rhs1 == NULL_TREE);
   19457 		  tree c = TREE_OPERAND (op11, 0);
   19458 		  if (TREE_CODE (c) == MODIFY_EXPR)
   19459 		    {
   19460 		      r = RECUR (TREE_OPERAND (c, 0));
   19461 		      c = TREE_OPERAND (c, 1);
   19462 		    }
   19463 		  gcc_assert (TREE_CODE (c) == EQ_EXPR);
   19464 		  rhs = RECUR (TREE_OPERAND (c, 1));
   19465 		  lhs = RECUR (TREE_OPERAND (op11, 2));
   19466 		  rhs1 = RECUR (TREE_OPERAND (op11, 1));
   19467 		}
   19468 	      else
   19469 		{
   19470 		  lhs = RECUR (TREE_OPERAND (op11, 0));
   19471 		  rhs = RECUR (TREE_OPERAND (op11, 1));
   19472 		}
   19473 	      opcode = TREE_CODE (op11);
   19474 	      if (opcode == MODIFY_EXPR)
   19475 		opcode = NOP_EXPR;
   19476 	    }
   19477 	  else
   19478 	    {
   19479 	      code = OMP_ATOMIC;
   19480 	      lhs = RECUR (TREE_OPERAND (op1, 0));
   19481 	      rhs = RECUR (TREE_OPERAND (op1, 1));
   19482 	    }
   19483 	  finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
   19484 			     lhs1, rhs1, r, tmp,
   19485 			     OMP_ATOMIC_MEMORY_ORDER (t), OMP_ATOMIC_WEAK (t));
   19486 	}
   19487       break;
   19488 
   19489     case TRANSACTION_EXPR:
   19490       {
   19491 	int flags = 0;
   19492 	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
   19493 	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
   19494 
   19495         if (TRANSACTION_EXPR_IS_STMT (t))
   19496           {
   19497 	    tree body = TRANSACTION_EXPR_BODY (t);
   19498 	    tree noex = NULL_TREE;
   19499 	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
   19500 	      {
   19501 		noex = MUST_NOT_THROW_COND (body);
   19502 		if (noex == NULL_TREE)
   19503 		  noex = boolean_true_node;
   19504 		body = TREE_OPERAND (body, 0);
   19505 	      }
   19506             stmt = begin_transaction_stmt (input_location, NULL, flags);
   19507             RECUR (body);
   19508             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
   19509           }
   19510         else
   19511           {
   19512             stmt = build_transaction_expr (EXPR_LOCATION (t),
   19513 					   RECUR (TRANSACTION_EXPR_BODY (t)),
   19514 					   flags, NULL_TREE);
   19515             RETURN (stmt);
   19516           }
   19517       }
   19518       break;
   19519 
   19520     case MUST_NOT_THROW_EXPR:
   19521       {
   19522 	tree op0 = RECUR (TREE_OPERAND (t, 0));
   19523 	tree cond = RECUR (MUST_NOT_THROW_COND (t));
   19524 	RETURN (build_must_not_throw_expr (op0, cond));
   19525       }
   19526 
   19527     case EXPR_PACK_EXPANSION:
   19528       error ("invalid use of pack expansion expression");
   19529       RETURN (error_mark_node);
   19530 
   19531     case NONTYPE_ARGUMENT_PACK:
   19532       error ("use %<...%> to expand argument pack");
   19533       RETURN (error_mark_node);
   19534 
   19535     case COMPOUND_EXPR:
   19536       tmp = RECUR (TREE_OPERAND (t, 0));
   19537       if (tmp == NULL_TREE)
   19538 	/* If the first operand was a statement, we're done with it.  */
   19539 	RETURN (RECUR (TREE_OPERAND (t, 1)));
   19540       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
   19541 				    RECUR (TREE_OPERAND (t, 1)),
   19542 				    templated_operator_saved_lookups (t),
   19543 				    complain));
   19544 
   19545     case PREDICT_EXPR:
   19546       RETURN (add_stmt (copy_node (t)));
   19547 
   19548     case ANNOTATE_EXPR:
   19549       {
   19550 	/* Although ANNOTATE_EXPR is an expression, it can only appear in
   19551 	   WHILE_COND, DO_COND or FOR_COND expressions, which are tsubsted
   19552 	   using tsubst_stmt rather than tsubst_expr and can contain
   19553 	   DECL_EXPRs.  */
   19554 	tree op1 = RECUR (TREE_OPERAND (t, 0));
   19555 	tree op2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl);
   19556 	tree op3 = tsubst_expr (TREE_OPERAND (t, 2), args, complain, in_decl);
   19557 	if (TREE_CODE (op2) == INTEGER_CST
   19558 	    && wi::to_widest (op2) == (int) annot_expr_unroll_kind)
   19559 	  op3 = cp_check_pragma_unroll (EXPR_LOCATION (TREE_OPERAND (t, 2)),
   19560 					op3);
   19561 	RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
   19562 			    TREE_TYPE (op1), op1, op2, op3));
   19563       }
   19564 
   19565     default:
   19566       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
   19567 
   19568       RETURN (tsubst_expr (t, args, complain, in_decl));
   19569     }
   19570 
   19571   RETURN (NULL_TREE);
   19572  out:
   19573   input_location = loc;
   19574   return r;
   19575 #undef RECUR
   19576 #undef RETURN
   19577 }
   19578 
   19579 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
   19580    function.  For description of the body see comment above
   19581    cp_parser_omp_declare_reduction_exprs.  */
   19582 
   19583 static void
   19584 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
   19585 {
   19586   if (t == NULL_TREE || t == error_mark_node)
   19587     return;
   19588 
   19589   gcc_assert (TREE_CODE (t) == STATEMENT_LIST && current_function_decl);
   19590 
   19591   tree_stmt_iterator tsi;
   19592   int i;
   19593   tree stmts[7];
   19594   memset (stmts, 0, sizeof stmts);
   19595   for (i = 0, tsi = tsi_start (t);
   19596        i < 7 && !tsi_end_p (tsi);
   19597        i++, tsi_next (&tsi))
   19598     stmts[i] = tsi_stmt (tsi);
   19599   gcc_assert (tsi_end_p (tsi));
   19600 
   19601   if (i >= 3)
   19602     {
   19603       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
   19604 		  && TREE_CODE (stmts[1]) == DECL_EXPR);
   19605       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
   19606 			     args, complain, in_decl);
   19607       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
   19608 			    args, complain, in_decl);
   19609       /* tsubsting a local var_decl leaves DECL_CONTEXT null, as we
   19610 	 expect to be pushing it.  */
   19611       DECL_CONTEXT (omp_out) = current_function_decl;
   19612       DECL_CONTEXT (omp_in) = current_function_decl;
   19613       keep_next_level (true);
   19614       tree block = begin_omp_structured_block ();
   19615       tsubst_stmt (stmts[2], args, complain, in_decl);
   19616       block = finish_omp_structured_block (block);
   19617       block = maybe_cleanup_point_expr_void (block);
   19618       add_decl_expr (omp_out);
   19619       copy_warning (omp_out, DECL_EXPR_DECL (stmts[0]));
   19620       add_decl_expr (omp_in);
   19621       finish_expr_stmt (block);
   19622     }
   19623   if (i >= 6)
   19624     {
   19625       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
   19626 		  && TREE_CODE (stmts[4]) == DECL_EXPR);
   19627       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
   19628 			      args, complain, in_decl);
   19629       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
   19630 			      args, complain, in_decl);
   19631       DECL_CONTEXT (omp_priv) = current_function_decl;
   19632       DECL_CONTEXT (omp_orig) = current_function_decl;
   19633       keep_next_level (true);
   19634       tree block = begin_omp_structured_block ();
   19635       tsubst_stmt (stmts[5], args, complain, in_decl);
   19636       block = finish_omp_structured_block (block);
   19637       block = maybe_cleanup_point_expr_void (block);
   19638       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
   19639       add_decl_expr (omp_priv);
   19640       add_decl_expr (omp_orig);
   19641       finish_expr_stmt (block);
   19642       if (i == 7)
   19643 	add_decl_expr (omp_orig);
   19644     }
   19645 }
   19646 
   19647 /* T is a postfix-expression that is not being used in a function
   19648    call.  Return the substituted version of T.  */
   19649 
   19650 static tree
   19651 tsubst_non_call_postfix_expression (tree t, tree args,
   19652 				    tsubst_flags_t complain,
   19653 				    tree in_decl)
   19654 {
   19655   if (TREE_CODE (t) == SCOPE_REF)
   19656     t = tsubst_qualified_id (t, args, complain, in_decl,
   19657 			     /*done=*/false, /*address_p=*/false);
   19658   else
   19659     t = tsubst_expr (t, args, complain, in_decl);
   19660 
   19661   return t;
   19662 }
   19663 
   19664 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
   19665    LAMBDA_EXPR_CAPTURE_LIST passed in LIST.  Do deduction for a previously
   19666    dependent init-capture.  EXPLICIT_P is true if the original list had
   19667    explicit captures.  */
   19668 
   19669 static void
   19670 prepend_one_capture (tree field, tree init, tree &list, bool explicit_p,
   19671 		     tsubst_flags_t complain)
   19672 {
   19673   if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
   19674     {
   19675       tree type = NULL_TREE;
   19676       if (!init)
   19677 	{
   19678 	  if (complain & tf_error)
   19679 	    error ("empty initializer in lambda init-capture");
   19680 	  init = error_mark_node;
   19681 	}
   19682       else if (TREE_CODE (init) == TREE_LIST)
   19683 	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
   19684       if (!type)
   19685 	type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
   19686       TREE_TYPE (field) = type;
   19687       cp_apply_type_quals_to_decl (cp_type_quals (type), field);
   19688     }
   19689   list = tree_cons (field, init, list);
   19690   LAMBDA_CAPTURE_EXPLICIT_P (list) = explicit_p;
   19691 }
   19692 
   19693 /* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
   19694    instantiation context.  Instantiating a pack expansion containing a lambda
   19695    might result in multiple lambdas all based on the same lambda in the
   19696    template.  */
   19697 
   19698 tree
   19699 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
   19700 {
   19701   tree oldfn = lambda_function (t);
   19702   in_decl = oldfn;
   19703 
   19704   args = add_extra_args (LAMBDA_EXPR_EXTRA_ARGS (t), args, complain, in_decl);
   19705   if (processing_template_decl
   19706       && (!in_template_context || any_dependent_template_arguments_p (args)))
   19707     {
   19708       /* Defer templated substitution into a lambda-expr if we lost the
   19709 	 necessary template context.  This may happen for a lambda-expr
   19710 	 used as a default template argument.
   19711 
   19712 	 Defer dependent substitution as well so that we don't prematurely
   19713 	 lower the level of a deduced return type or any other auto or
   19714 	 template parameter belonging to the lambda.  */
   19715       t = copy_node (t);
   19716       LAMBDA_EXPR_EXTRA_ARGS (t) = NULL_TREE;
   19717       LAMBDA_EXPR_EXTRA_ARGS (t) = build_extra_args (t, args, complain);
   19718       return t;
   19719     }
   19720   if (LAMBDA_EXPR_EXTRA_ARGS (t))
   19721     {
   19722       /* If we deferred substitution into this lambda, then its original
   19723 	 context (e.g. default template argument context) might be unrelated
   19724 	 to the current context it's embedded in.  After add_extra_args though,
   19725 	 the innermost levels of 'args' will correspond to the lambda context,
   19726 	 so get rid of all unrelated levels.  */
   19727       tree ctx_parms = DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (oldfn));
   19728       if (generic_lambda_fn_p (oldfn))
   19729 	ctx_parms = TREE_CHAIN (ctx_parms);
   19730       if (TMPL_ARGS_DEPTH (args) > TMPL_PARMS_DEPTH (ctx_parms))
   19731 	args = get_innermost_template_args (args, TMPL_PARMS_DEPTH (ctx_parms));
   19732     }
   19733 
   19734   tree r = build_lambda_expr ();
   19735 
   19736   LAMBDA_EXPR_LOCATION (r)
   19737     = LAMBDA_EXPR_LOCATION (t);
   19738   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
   19739     = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
   19740   if (tree ti = LAMBDA_EXPR_REGEN_INFO (t))
   19741     LAMBDA_EXPR_REGEN_INFO (r)
   19742       = build_template_info (t, add_to_template_args (TI_ARGS (ti),
   19743 						      preserve_args (args)));
   19744   else
   19745     LAMBDA_EXPR_REGEN_INFO (r)
   19746       = build_template_info (t, preserve_args (args));
   19747 
   19748   gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
   19749 	      && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
   19750 
   19751   vec<tree,va_gc>* field_packs = NULL;
   19752   unsigned name_independent_cnt = 0;
   19753   for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
   19754        cap = TREE_CHAIN (cap))
   19755     {
   19756       tree ofield = TREE_PURPOSE (cap);
   19757       tree init = TREE_VALUE (cap);
   19758       if (PACK_EXPANSION_P (init))
   19759 	init = tsubst_pack_expansion (init, args, complain, in_decl);
   19760       else
   19761 	init = tsubst_expr (init, args, complain, in_decl);
   19762 
   19763       if (init == error_mark_node)
   19764 	return error_mark_node;
   19765 
   19766       if (init && TREE_CODE (init) == TREE_LIST)
   19767 	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
   19768 
   19769       if (!processing_template_decl
   19770 	  && init && TREE_CODE (init) != TREE_VEC
   19771 	  && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
   19772 	{
   19773 	  /* For a VLA, simply tsubsting the field type won't work, we need to
   19774 	     go through add_capture again.  XXX do we want to do this for all
   19775 	     captures?  */
   19776 	  tree name = (get_identifier
   19777 		       (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
   19778 	  tree ftype = TREE_TYPE (ofield);
   19779 	  bool by_ref = (TYPE_REF_P (ftype)
   19780 			 || (TREE_CODE (ftype) == DECLTYPE_TYPE
   19781 			     && DECLTYPE_FOR_REF_CAPTURE (ftype)));
   19782 	  add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield),
   19783 		       &name_independent_cnt);
   19784 	  continue;
   19785 	}
   19786 
   19787       if (PACK_EXPANSION_P (ofield))
   19788 	ofield = PACK_EXPANSION_PATTERN (ofield);
   19789       tree field = tsubst_decl (ofield, args, complain);
   19790 
   19791       if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
   19792 	{
   19793 	  /* Remember these for when we've pushed local_specializations.  */
   19794 	  vec_safe_push (field_packs, ofield);
   19795 	  vec_safe_push (field_packs, field);
   19796 	}
   19797 
   19798       if (field == error_mark_node)
   19799 	return error_mark_node;
   19800 
   19801       if (TREE_CODE (field) == TREE_VEC)
   19802 	{
   19803 	  int len = TREE_VEC_LENGTH (field);
   19804 	  gcc_assert (TREE_CODE (init) == TREE_VEC
   19805 		      && TREE_VEC_LENGTH (init) == len);
   19806 	  for (int i = 0; i < len; ++i)
   19807 	    prepend_one_capture (TREE_VEC_ELT (field, i),
   19808 				 TREE_VEC_ELT (init, i),
   19809 				 LAMBDA_EXPR_CAPTURE_LIST (r),
   19810 				 LAMBDA_CAPTURE_EXPLICIT_P (cap),
   19811 				 complain);
   19812 	}
   19813       else
   19814 	{
   19815 	  prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
   19816 			       LAMBDA_CAPTURE_EXPLICIT_P (cap), complain);
   19817 
   19818 	  if (id_equal (DECL_NAME (field), "__this"))
   19819 	    LAMBDA_EXPR_THIS_CAPTURE (r) = field;
   19820 	}
   19821     }
   19822 
   19823   tree type = begin_lambda_type (r);
   19824   if (type == error_mark_node)
   19825     {
   19826       gcc_checking_assert (!(complain & tf_error) || seen_error ());
   19827       return error_mark_node;
   19828     }
   19829 
   19830   if (LAMBDA_EXPR_EXTRA_SCOPE (t))
   19831     record_lambda_scope (r);
   19832   else if (TYPE_NAMESPACE_SCOPE_P (TREE_TYPE (t)))
   19833     /* If we're pushed into another scope (PR105652), fix it.  */
   19834     TYPE_CONTEXT (type) = DECL_CONTEXT (TYPE_NAME (type))
   19835       = TYPE_CONTEXT (TREE_TYPE (t));
   19836   record_lambda_scope_discriminator (r);
   19837 
   19838   /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
   19839   determine_visibility (TYPE_NAME (type));
   19840 
   19841   register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
   19842 
   19843   tree oldtmpl = (generic_lambda_fn_p (oldfn)
   19844 		  ? DECL_TI_TEMPLATE (oldfn)
   19845 		  : NULL_TREE);
   19846 
   19847   tree tparms = NULL_TREE;
   19848   if (oldtmpl)
   19849     tparms = tsubst_template_parms (DECL_TEMPLATE_PARMS (oldtmpl), args, complain);
   19850 
   19851   tree fntype = static_fn_type (oldfn);
   19852 
   19853   tree saved_ctp = current_template_parms;
   19854   if (oldtmpl)
   19855     {
   19856       ++processing_template_decl;
   19857       current_template_parms = tparms;
   19858     }
   19859   fntype = tsubst (fntype, args, complain, in_decl);
   19860   if (oldtmpl)
   19861     {
   19862       current_template_parms = saved_ctp;
   19863       --processing_template_decl;
   19864     }
   19865 
   19866   if (fntype == error_mark_node)
   19867     r = error_mark_node;
   19868   else
   19869     {
   19870       /* The body of a lambda-expression is not a subexpression of the
   19871 	 enclosing expression.  Parms are to have DECL_CHAIN tsubsted,
   19872 	 which would be skipped if cp_unevaluated_operand.  */
   19873       cp_evaluated ev;
   19874 
   19875       /* Fix the type of 'this'.
   19876 	 For static and xobj member functions we use this to transport the
   19877 	 lambda's closure type.  It appears that in the regular case the
   19878 	 object parameter is still pulled off, and then re-added again anyway.
   19879 	 So perhaps we could do something better here?  */
   19880       fntype = build_memfn_type (fntype, type,
   19881 				 type_memfn_quals (fntype),
   19882 				 type_memfn_rqual (fntype));
   19883       tree inst = (oldtmpl
   19884 		   ? tsubst_template_decl (oldtmpl, args, complain,
   19885 					   fntype, tparms)
   19886 		   : tsubst_function_decl (oldfn, args, complain, fntype));
   19887       if (inst == error_mark_node)
   19888 	{
   19889 	  r = error_mark_node;
   19890 	  goto out;
   19891 	}
   19892       finish_member_declaration (inst);
   19893       record_lambda_scope_sig_discriminator (r, inst);
   19894 
   19895       tree fn = oldtmpl ? DECL_TEMPLATE_RESULT (inst) : inst;
   19896 
   19897       /* Let finish_function set this.  */
   19898       DECL_DECLARED_CONSTEXPR_P (fn) = false;
   19899 
   19900       bool nested = cfun;
   19901       if (nested)
   19902 	push_function_context ();
   19903       else
   19904 	/* Still increment function_depth so that we don't GC in the
   19905 	   middle of an expression.  */
   19906 	++function_depth;
   19907 
   19908       local_specialization_stack s (lss_copy);
   19909 
   19910       bool save_in_consteval_if_p = in_consteval_if_p;
   19911       in_consteval_if_p = false;
   19912 
   19913       tree body = start_lambda_function (fn, r);
   19914 
   19915       /* Now record them for lookup_init_capture_pack.  */
   19916       int fplen = vec_safe_length (field_packs);
   19917       for (int i = 0; i < fplen; )
   19918 	{
   19919 	  tree pack = (*field_packs)[i++];
   19920 	  tree inst = (*field_packs)[i++];
   19921 	  register_local_specialization (inst, pack);
   19922 	}
   19923       release_tree_vector (field_packs);
   19924 
   19925       register_parameter_specializations (oldfn, fn);
   19926 
   19927       if (oldtmpl)
   19928 	{
   19929 	  /* We might not partially instantiate some parts of the function, so
   19930 	     copy these flags from the original template.  */
   19931 	  language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
   19932 	  current_function_returns_value = ol->returns_value;
   19933 	  current_function_returns_null = ol->returns_null;
   19934 	  current_function_returns_abnormally = ol->returns_abnormally;
   19935 	  current_function_infinite_loop = ol->infinite_loop;
   19936 	}
   19937 
   19938       /* [temp.deduct] A lambda-expression appearing in a function type or a
   19939 	 template parameter is not considered part of the immediate context for
   19940 	 the purposes of template argument deduction. */
   19941       complain = tf_warning_or_error;
   19942 
   19943       tree saved = DECL_SAVED_TREE (oldfn);
   19944       if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
   19945 	/* We already have a body block from start_lambda_function, we don't
   19946 	   need another to confuse NRV (91217).  */
   19947 	saved = BIND_EXPR_BODY (saved);
   19948 
   19949       tsubst_stmt (saved, args, complain, r);
   19950 
   19951       finish_lambda_function (body);
   19952 
   19953       in_consteval_if_p = save_in_consteval_if_p;
   19954 
   19955       if (nested)
   19956 	pop_function_context ();
   19957       else
   19958 	--function_depth;
   19959 
   19960       /* The capture list was built up in reverse order; fix that now.  */
   19961       LAMBDA_EXPR_CAPTURE_LIST (r)
   19962 	= nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
   19963 
   19964       LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
   19965 
   19966       maybe_add_lambda_conv_op (type);
   19967     }
   19968 
   19969 out:
   19970   finish_struct (type, /*attr*/NULL_TREE);
   19971 
   19972   insert_pending_capture_proxies ();
   19973 
   19974   return r;
   19975 }
   19976 
   19977 /* Subroutine of maybe_fold_fn_template_args.  */
   19978 
   19979 static bool
   19980 fold_targs_r (tree targs, tsubst_flags_t complain)
   19981 {
   19982   int len = TREE_VEC_LENGTH (targs);
   19983   for (int i = 0; i < len; ++i)
   19984     {
   19985       tree &elt = TREE_VEC_ELT (targs, i);
   19986       if (!elt || TYPE_P (elt)
   19987 	  || TREE_CODE (elt) == TEMPLATE_DECL)
   19988 	continue;
   19989       if (TREE_CODE (elt) == NONTYPE_ARGUMENT_PACK)
   19990 	{
   19991 	  if (!fold_targs_r (ARGUMENT_PACK_ARGS (elt), complain))
   19992 	    return false;
   19993 	}
   19994       else if (/* We can only safely preevaluate scalar prvalues.  */
   19995 	       SCALAR_TYPE_P (TREE_TYPE (elt))
   19996 	       && !glvalue_p (elt)
   19997 	       && !TREE_CONSTANT (elt))
   19998 	{
   19999 	  elt = cxx_constant_value (elt, complain);
   20000 	  if (elt == error_mark_node)
   20001 	    return false;
   20002 	}
   20003     }
   20004 
   20005   return true;
   20006 }
   20007 
   20008 /* Try to do constant evaluation of any explicit template arguments in FN
   20009    before overload resolution, to get any errors only once.  Return true iff
   20010    we didn't have any problems folding.  */
   20011 
   20012 static bool
   20013 maybe_fold_fn_template_args (tree fn, tsubst_flags_t complain)
   20014 {
   20015   if (processing_template_decl || fn == NULL_TREE)
   20016     return true;
   20017   if (fn == error_mark_node)
   20018     return false;
   20019   if (TREE_CODE (fn) == OFFSET_REF
   20020       || TREE_CODE (fn) == COMPONENT_REF)
   20021     fn = TREE_OPERAND (fn, 1);
   20022   if (BASELINK_P (fn))
   20023     fn = BASELINK_FUNCTIONS (fn);
   20024   if (TREE_CODE (fn) != TEMPLATE_ID_EXPR)
   20025     return true;
   20026   tree targs = TREE_OPERAND (fn, 1);
   20027   if (targs == NULL_TREE)
   20028     return true;
   20029   if (targs == error_mark_node)
   20030     return false;
   20031   return fold_targs_r (targs, complain);
   20032 }
   20033 
   20034 /* Helper function for tsubst_expr CALL_EXPR and ARRAY_REF handling.  */
   20035 
   20036 static void
   20037 tsubst_call_args (tree t, tree args, tsubst_flags_t complain,
   20038 		  tree in_decl, releasing_vec &call_args)
   20039 {
   20040   unsigned int nargs = call_expr_nargs (t);
   20041   for (unsigned int i = 0; i < nargs; ++i)
   20042     {
   20043       tree arg = CALL_EXPR_ARG (t, i);
   20044 
   20045       if (!PACK_EXPANSION_P (arg))
   20046 	vec_safe_push (call_args, tsubst_expr (arg, args, complain, in_decl));
   20047       else
   20048 	{
   20049 	  /* Expand the pack expansion and push each entry onto CALL_ARGS.  */
   20050 	  arg = tsubst_pack_expansion (arg, args, complain, in_decl);
   20051 	  if (TREE_CODE (arg) == TREE_VEC)
   20052 	    {
   20053 	      unsigned int len, j;
   20054 
   20055 	      len = TREE_VEC_LENGTH (arg);
   20056 	      for (j = 0; j < len; ++j)
   20057 		{
   20058 		  tree value = TREE_VEC_ELT (arg, j);
   20059 		  if (value != NULL_TREE)
   20060 		    value = convert_from_reference (value);
   20061 		  vec_safe_push (call_args, value);
   20062 		}
   20063 	    }
   20064 	  else
   20065 	    /* A partial substitution.  Add one entry.  */
   20066 	    vec_safe_push (call_args, arg);
   20067 	}
   20068     }
   20069 }
   20070 
   20071 /* Like tsubst but deals with expressions and performs semantic
   20072    analysis.  */
   20073 
   20074 tree
   20075 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
   20076 {
   20077 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
   20078 #define RECUR(NODE)						\
   20079   tsubst_expr (NODE, args, complain, in_decl)
   20080 
   20081   tree retval, op1;
   20082   location_t save_loc;
   20083 
   20084   if (t == NULL_TREE || t == error_mark_node)
   20085     return t;
   20086 
   20087   save_loc = input_location;
   20088   if (location_t eloc = cp_expr_location (t))
   20089     input_location = eloc;
   20090 
   20091   /* N3276 decltype magic only applies to calls at the top level or on the
   20092      right side of a comma.  */
   20093   tsubst_flags_t decltype_flag = (complain & tf_decltype);
   20094   complain &= ~tf_decltype;
   20095 
   20096   /* This flag only applies to id-expressions at the top level, and
   20097      controls resolution thereof.  */
   20098   tsubst_flags_t no_name_lookup_flag = (complain & tf_no_name_lookup);
   20099   complain &= ~tf_no_name_lookup;
   20100 
   20101   if (!no_name_lookup_flag)
   20102     if (tree d = maybe_dependent_member_ref (t, args, complain, in_decl))
   20103       return d;
   20104 
   20105   switch (TREE_CODE (t))
   20106     {
   20107     case USING_DECL:
   20108       t = DECL_NAME (t);
   20109       /* Fall through.  */
   20110     case IDENTIFIER_NODE:
   20111       {
   20112 	tree decl;
   20113 	cp_id_kind idk;
   20114 	const char *error_msg;
   20115 
   20116 	if (IDENTIFIER_CONV_OP_P (t))
   20117 	  {
   20118 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   20119 	    t = make_conv_op_name (new_type);
   20120 	  }
   20121 
   20122 	if (no_name_lookup_flag)
   20123 	  RETURN (t);
   20124 
   20125 	/* Look up the name.  */
   20126 	decl = lookup_name (t);
   20127 
   20128 	/* By convention, expressions use ERROR_MARK_NODE to indicate
   20129 	   failure, not NULL_TREE.  */
   20130 	if (decl == NULL_TREE)
   20131 	  decl = error_mark_node;
   20132 
   20133 	decl = finish_id_expression (t, decl, NULL_TREE,
   20134 				     &idk,
   20135 				     /*i_c_e_p=*/false,
   20136 				     /*allow_i_c_e_p=*/true,
   20137 				     /*non_i_c_e_p=*/nullptr,
   20138 				     /*template_p=*/false,
   20139 				     /*done=*/true,
   20140 				     /*address_p=*/false,
   20141 				     /*template_arg_p=*/false,
   20142 				     &error_msg,
   20143 				     input_location);
   20144 	if (error_msg)
   20145 	  error (error_msg);
   20146 	if (identifier_p (decl))
   20147 	  {
   20148 	    if (complain & tf_error)
   20149 	      unqualified_name_lookup_error (decl);
   20150 	    decl = error_mark_node;
   20151 	  }
   20152 	RETURN (decl);
   20153       }
   20154 
   20155     case TEMPLATE_ID_EXPR:
   20156       {
   20157 	tree object;
   20158 	tree templ = TREE_OPERAND (t, 0);
   20159 	tree targs = TREE_OPERAND (t, 1);
   20160 
   20161 	if (no_name_lookup_flag)
   20162 	  templ = tsubst_name (templ, args, complain, in_decl);
   20163 	else
   20164 	  templ = tsubst_expr (templ, args, complain, in_decl);
   20165 
   20166 	if (targs)
   20167 	  targs = tsubst_template_args (targs, args, complain, in_decl);
   20168 	if (targs == error_mark_node)
   20169 	  RETURN (error_mark_node);
   20170 
   20171 	if (TREE_CODE (templ) == SCOPE_REF)
   20172 	  {
   20173 	    tree name = TREE_OPERAND (templ, 1);
   20174 	    tree tid = lookup_template_function (name, targs);
   20175 	    TREE_OPERAND (templ, 1) = tid;
   20176 	    RETURN (templ);
   20177 	  }
   20178 
   20179 	if (concept_definition_p (templ))
   20180 	  {
   20181 	    tree check = build_concept_check (templ, targs, complain);
   20182 	    if (check == error_mark_node)
   20183 	      RETURN (error_mark_node);
   20184 
   20185 	    tree id = unpack_concept_check (check);
   20186 
   20187 	    /* If we built a function concept check, return the underlying
   20188 	       template-id. So we can evaluate it as a function call.  */
   20189 	    if (function_concept_p (TREE_OPERAND (id, 0)))
   20190 	      RETURN (id);
   20191 
   20192 	    RETURN (check);
   20193 	  }
   20194 
   20195 	if (variable_template_p (templ))
   20196 	  {
   20197 	    if (no_name_lookup_flag)
   20198 	      RETURN (lookup_template_variable (templ, targs, complain));
   20199 
   20200 	    tree r = lookup_and_finish_template_variable (templ, targs,
   20201 							  complain);
   20202 	    r = convert_from_reference (r);
   20203 	    r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
   20204 	    RETURN (r);
   20205 	  }
   20206 
   20207 	if (TREE_CODE (templ) == COMPONENT_REF)
   20208 	  {
   20209 	    object = TREE_OPERAND (templ, 0);
   20210 	    templ = TREE_OPERAND (templ, 1);
   20211 	  }
   20212 	else
   20213 	  object = NULL_TREE;
   20214 
   20215 	tree tid = lookup_template_function (templ, targs);
   20216 	protected_set_expr_location (tid, EXPR_LOCATION (t));
   20217 
   20218 	if (object)
   20219 	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
   20220 			 object, tid, NULL_TREE));
   20221 	else if (no_name_lookup_flag)
   20222 	  RETURN (tid);
   20223 	else if (identifier_p (templ))
   20224 	  {
   20225 	    /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
   20226 	       name lookup found nothing when parsing the template name.  */
   20227 	    gcc_assert (cxx_dialect >= cxx20 || seen_error ());
   20228 	    RETURN (tid);
   20229 	  }
   20230 	else
   20231 	  RETURN (baselink_for_fns (tid));
   20232       }
   20233 
   20234     case INDIRECT_REF:
   20235       {
   20236 	tree r = RECUR (TREE_OPERAND (t, 0));
   20237 
   20238 	if (REFERENCE_REF_P (t))
   20239 	  {
   20240 	    /* A type conversion to reference type will be enclosed in
   20241 	       such an indirect ref, but the substitution of the cast
   20242 	       will have also added such an indirect ref.  */
   20243 	    r = convert_from_reference (r);
   20244 	  }
   20245 	else
   20246 	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
   20247 				    templated_operator_saved_lookups (t),
   20248 				    complain|decltype_flag);
   20249 
   20250 	if (REF_PARENTHESIZED_P (t))
   20251 	  r = force_paren_expr (r);
   20252 
   20253 	RETURN (r);
   20254       }
   20255 
   20256     case MEM_REF:
   20257       {
   20258 	tree op0 = RECUR (TREE_OPERAND (t, 0));
   20259 	tree op1 = RECUR (TREE_OPERAND (t, 0));
   20260 	tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   20261 	RETURN (build2_loc (EXPR_LOCATION (t), MEM_REF, new_type, op0, op1));
   20262       }
   20263 
   20264     case NOP_EXPR:
   20265       {
   20266 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   20267 	tree op0 = RECUR (TREE_OPERAND (t, 0));
   20268 	RETURN (build_nop (type, op0));
   20269       }
   20270 
   20271     case IMPLICIT_CONV_EXPR:
   20272       {
   20273 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   20274 	if (type == error_mark_node)
   20275 	  RETURN (error_mark_node);
   20276 	tree expr = RECUR (TREE_OPERAND (t, 0));
   20277 	if (dependent_type_p (type) || type_dependent_expression_p (expr))
   20278 	  {
   20279 	    retval = copy_node (t);
   20280 	    TREE_TYPE (retval) = type;
   20281 	    TREE_OPERAND (retval, 0) = expr;
   20282 	    RETURN (retval);
   20283 	  }
   20284 	if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
   20285 	  {
   20286 	    tree r = convert_nontype_argument (type, expr, complain);
   20287 	    if (r == NULL_TREE)
   20288 	      r = error_mark_node;
   20289 	    RETURN (r);
   20290 	  }
   20291 	int flags = LOOKUP_IMPLICIT;
   20292 	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
   20293 	  flags = LOOKUP_NORMAL;
   20294 	if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
   20295 	  flags |= LOOKUP_NO_NARROWING;
   20296 	RETURN (perform_implicit_conversion_flags (type, expr, complain,
   20297 						  flags));
   20298       }
   20299 
   20300     case CONVERT_EXPR:
   20301       {
   20302 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   20303 	tree op0 = RECUR (TREE_OPERAND (t, 0));
   20304 	if (op0 == error_mark_node)
   20305 	  RETURN (error_mark_node);
   20306 	RETURN (build1 (CONVERT_EXPR, type, op0));
   20307       }
   20308 
   20309     case CAST_EXPR:
   20310     case REINTERPRET_CAST_EXPR:
   20311     case CONST_CAST_EXPR:
   20312     case DYNAMIC_CAST_EXPR:
   20313     case STATIC_CAST_EXPR:
   20314       {
   20315 	tree type;
   20316 	tree op, r = NULL_TREE;
   20317 
   20318 	tsubst_flags_t tcomplain = complain;
   20319 	if (TREE_CODE (t) == CAST_EXPR)
   20320 	  tcomplain |= tf_tst_ok;
   20321 	type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
   20322 
   20323 	op = RECUR (TREE_OPERAND (t, 0));
   20324 
   20325 	warning_sentinel s(warn_useless_cast);
   20326 	warning_sentinel s2(warn_ignored_qualifiers);
   20327 	warning_sentinel s3(warn_int_in_bool_context);
   20328 	switch (TREE_CODE (t))
   20329 	  {
   20330 	  case CAST_EXPR:
   20331 	    r = build_functional_cast (input_location, type, op, complain);
   20332 	    break;
   20333 	  case REINTERPRET_CAST_EXPR:
   20334 	    r = build_reinterpret_cast (input_location, type, op, complain);
   20335 	    break;
   20336 	  case CONST_CAST_EXPR:
   20337 	    r = build_const_cast (input_location, type, op, complain);
   20338 	    break;
   20339 	  case DYNAMIC_CAST_EXPR:
   20340 	    r = build_dynamic_cast (input_location, type, op, complain);
   20341 	    break;
   20342 	  case STATIC_CAST_EXPR:
   20343 	    r = build_static_cast (input_location, type, op, complain);
   20344 	    if (IMPLICIT_RVALUE_P (t))
   20345 	      set_implicit_rvalue_p (r);
   20346 	    break;
   20347 	  default:
   20348 	    gcc_unreachable ();
   20349 	  }
   20350 
   20351 	RETURN (r);
   20352       }
   20353 
   20354     case BIT_CAST_EXPR:
   20355       {
   20356 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   20357 	tree op0 = RECUR (TREE_OPERAND (t, 0));
   20358 	RETURN (cp_build_bit_cast (EXPR_LOCATION (t), type, op0, complain));
   20359       }
   20360 
   20361     case POSTDECREMENT_EXPR:
   20362     case POSTINCREMENT_EXPR:
   20363       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
   20364 						args, complain, in_decl);
   20365       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
   20366 				templated_operator_saved_lookups (t),
   20367 				complain|decltype_flag));
   20368 
   20369     case BIT_NOT_EXPR:
   20370       if (identifier_p (TREE_OPERAND (t, 0)))
   20371 	{
   20372 	  gcc_checking_assert (no_name_lookup_flag);
   20373 	  RETURN (t);
   20374 	}
   20375       else if (TYPE_P (TREE_OPERAND (t, 0)))
   20376 	{
   20377 	  gcc_checking_assert (no_name_lookup_flag);
   20378 	  tree op0 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
   20379 	  RETURN (build_min_nt_loc (EXPR_LOCATION (t), BIT_NOT_EXPR, op0));
   20380 	}
   20381       /* Fall through.  */
   20382     case PREDECREMENT_EXPR:
   20383     case PREINCREMENT_EXPR:
   20384     case NEGATE_EXPR:
   20385     case ABS_EXPR:
   20386     case TRUTH_NOT_EXPR:
   20387     case UNARY_PLUS_EXPR:  /* Unary + */
   20388     case REALPART_EXPR:
   20389     case IMAGPART_EXPR:
   20390       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
   20391 				RECUR (TREE_OPERAND (t, 0)),
   20392 				templated_operator_saved_lookups (t),
   20393 				complain|decltype_flag));
   20394 
   20395     case EXCESS_PRECISION_EXPR:
   20396       {
   20397 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   20398 	tree op0 = RECUR (TREE_OPERAND (t, 0));
   20399 	if (TREE_CODE (op0) == EXCESS_PRECISION_EXPR)
   20400 	  RETURN (op0);
   20401 	RETURN (build1_loc (EXPR_LOCATION (t), EXCESS_PRECISION_EXPR,
   20402 			    type, op0));
   20403       }
   20404 
   20405     case FIX_TRUNC_EXPR:
   20406       /* convert_like should have created an IMPLICIT_CONV_EXPR.  */
   20407       gcc_unreachable ();
   20408 
   20409     case ADDR_EXPR:
   20410       op1 = TREE_OPERAND (t, 0);
   20411       if (TREE_CODE (op1) == LABEL_DECL)
   20412 	RETURN (finish_label_address_expr (DECL_NAME (op1),
   20413 					  EXPR_LOCATION (op1)));
   20414       if (TREE_CODE (op1) == SCOPE_REF)
   20415 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
   20416 				   /*done=*/true, /*address_p=*/true);
   20417       else
   20418 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
   20419 						  in_decl);
   20420       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
   20421 				templated_operator_saved_lookups (t),
   20422 				complain|decltype_flag));
   20423 
   20424     case PLUS_EXPR:
   20425     case MINUS_EXPR:
   20426     case MULT_EXPR:
   20427     case TRUNC_DIV_EXPR:
   20428     case CEIL_DIV_EXPR:
   20429     case FLOOR_DIV_EXPR:
   20430     case ROUND_DIV_EXPR:
   20431     case EXACT_DIV_EXPR:
   20432     case BIT_AND_EXPR:
   20433     case BIT_IOR_EXPR:
   20434     case BIT_XOR_EXPR:
   20435     case TRUNC_MOD_EXPR:
   20436     case FLOOR_MOD_EXPR:
   20437     case TRUTH_ANDIF_EXPR:
   20438     case TRUTH_ORIF_EXPR:
   20439     case TRUTH_AND_EXPR:
   20440     case TRUTH_OR_EXPR:
   20441     case RSHIFT_EXPR:
   20442     case LSHIFT_EXPR:
   20443     case EQ_EXPR:
   20444     case NE_EXPR:
   20445     case MAX_EXPR:
   20446     case MIN_EXPR:
   20447     case LE_EXPR:
   20448     case GE_EXPR:
   20449     case LT_EXPR:
   20450     case GT_EXPR:
   20451     case SPACESHIP_EXPR:
   20452     case MEMBER_REF:
   20453     case DOTSTAR_EXPR:
   20454       {
   20455 	/* If either OP0 or OP1 was value- or type-dependent, suppress
   20456 	   warnings that depend on the range of the types involved.  */
   20457 	tree op0 = TREE_OPERAND (t, 0);
   20458 	tree op1 = TREE_OPERAND (t, 1);
   20459 	const bool was_dep = (dependent_operand_p (op0)
   20460 			      || dependent_operand_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       if (no_name_lookup_flag)
   20502 	{
   20503 	  tree op0 = tsubst_scope (TREE_OPERAND (t, 0), args, complain, in_decl);
   20504 	  tree op1 = tsubst_name (TREE_OPERAND (t, 1), args, complain, in_decl);
   20505 	  RETURN (build_qualified_name (/*type=*/NULL_TREE, op0, op1,
   20506 					QUALIFIED_NAME_IS_TEMPLATE (t)));
   20507 	}
   20508       else
   20509 	RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
   20510 				    /*address_p=*/false));
   20511 
   20512     case BASELINK:
   20513       RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
   20514 			       args, complain, in_decl));
   20515 
   20516     case ARRAY_REF:
   20517       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
   20518 						args, complain, in_decl);
   20519       if (TREE_CODE (TREE_OPERAND (t, 1)) == CALL_EXPR
   20520 	  && (CALL_EXPR_FN (TREE_OPERAND (t, 1))
   20521 	      == ovl_op_identifier (ARRAY_REF)))
   20522 	{
   20523 	  tree c = TREE_OPERAND (t, 1);
   20524 	  releasing_vec index_exp_list;
   20525 	  tsubst_call_args (c, args, complain, in_decl, index_exp_list);
   20526 
   20527 	  tree r;
   20528 	  if (vec_safe_length (index_exp_list) == 1
   20529 	      && !PACK_EXPANSION_P (index_exp_list[0]))
   20530 	    r = grok_array_decl (EXPR_LOCATION (t), op1,
   20531 				 index_exp_list[0], NULL,
   20532 				 complain | decltype_flag);
   20533 	  else
   20534 	    r = grok_array_decl (EXPR_LOCATION (t), op1,
   20535 				 NULL_TREE, &index_exp_list,
   20536 				 complain | decltype_flag);
   20537 	  RETURN (r);
   20538 	}
   20539       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
   20540 				 RECUR (TREE_OPERAND (t, 1)),
   20541 				 complain|decltype_flag));
   20542 
   20543     case OMP_ARRAY_SECTION:
   20544       {
   20545 	tree op0 = RECUR (TREE_OPERAND (t, 0));
   20546 	tree op1 = NULL_TREE, op2 = NULL_TREE;
   20547 	if (op0 == error_mark_node)
   20548 	  RETURN (error_mark_node);
   20549 	if (TREE_OPERAND (t, 1))
   20550 	  {
   20551 	    op1 = RECUR (TREE_OPERAND (t, 1));
   20552 	    if (op1 == error_mark_node)
   20553 	      RETURN (error_mark_node);
   20554 	  }
   20555 	if (TREE_OPERAND (t, 2))
   20556 	  {
   20557 	    op2 = RECUR (TREE_OPERAND (t, 2));
   20558 	    if (op2 == error_mark_node)
   20559 	      RETURN (error_mark_node);
   20560 	  }
   20561 	RETURN (build_omp_array_section (EXPR_LOCATION (t), op0, op1, op2));
   20562       }
   20563 
   20564     case SIZEOF_EXPR:
   20565       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
   20566 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
   20567 	{
   20568 	  tree expanded, op = TREE_OPERAND (t, 0);
   20569 	  int len = 0;
   20570 
   20571 	  if (SIZEOF_EXPR_TYPE_P (t))
   20572 	    op = TREE_TYPE (op);
   20573 
   20574 	  ++cp_unevaluated_operand;
   20575 	  ++c_inhibit_evaluation_warnings;
   20576 	  /* We only want to compute the number of arguments.  */
   20577 	  if (PACK_EXPANSION_P (op))
   20578 	    expanded = tsubst_pack_expansion (op, args, complain, in_decl);
   20579 	  else
   20580 	    expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
   20581 					     args, complain, in_decl);
   20582 	  --cp_unevaluated_operand;
   20583 	  --c_inhibit_evaluation_warnings;
   20584 
   20585 	  if (TREE_CODE (expanded) == TREE_VEC)
   20586 	    {
   20587 	      len = TREE_VEC_LENGTH (expanded);
   20588 	      /* Set TREE_USED for the benefit of -Wunused.  */
   20589 	      for (int i = 0; i < len; i++)
   20590 		if (DECL_P (TREE_VEC_ELT (expanded, i)))
   20591 		  TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
   20592 	    }
   20593 
   20594 	  if (expanded == error_mark_node)
   20595 	    RETURN (error_mark_node);
   20596 	  else if (PACK_EXPANSION_P (expanded)
   20597 		   || (TREE_CODE (expanded) == TREE_VEC
   20598 		       && pack_expansion_args_count (expanded)))
   20599 
   20600 	    {
   20601 	      if (PACK_EXPANSION_P (expanded))
   20602 		/* OK.  */;
   20603 	      else
   20604 		expanded = make_argument_pack (expanded);
   20605 
   20606 	      if (TYPE_P (expanded))
   20607 		RETURN (cxx_sizeof_or_alignof_type (input_location,
   20608 						    expanded, SIZEOF_EXPR,
   20609 						    false,
   20610 						    complain & tf_error));
   20611 	      else
   20612 		RETURN (cxx_sizeof_or_alignof_expr (input_location,
   20613 						    expanded, SIZEOF_EXPR,
   20614 						    false,
   20615 						    complain & tf_error));
   20616 	    }
   20617 	  else
   20618 	    RETURN (build_int_cst (size_type_node, len));
   20619 	}
   20620       /* Fall through */
   20621 
   20622     case ALIGNOF_EXPR:
   20623       {
   20624 	tree r;
   20625 
   20626 	op1 = TREE_OPERAND (t, 0);
   20627 	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
   20628 	  op1 = TREE_TYPE (op1);
   20629 	bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
   20630 			    && ALIGNOF_EXPR_STD_P (t));
   20631         if (!args)
   20632 	  {
   20633 	    /* When there are no ARGS, we are trying to evaluate a
   20634 	       non-dependent expression from the parser.  Trying to do
   20635 	       the substitutions may not work.  */
   20636 	    if (!TYPE_P (op1))
   20637 	      op1 = TREE_TYPE (op1);
   20638 	  }
   20639 	else
   20640 	  {
   20641 	    ++cp_unevaluated_operand;
   20642 	    ++c_inhibit_evaluation_warnings;
   20643 	    if (TYPE_P (op1))
   20644 	      op1 = tsubst (op1, args, complain, in_decl);
   20645 	    else
   20646 	      op1 = tsubst_expr (op1, args, complain, in_decl);
   20647 	    --cp_unevaluated_operand;
   20648 	    --c_inhibit_evaluation_warnings;
   20649 	  }
   20650         if (TYPE_P (op1))
   20651 	  r = cxx_sizeof_or_alignof_type (input_location,
   20652 					  op1, TREE_CODE (t), std_alignof,
   20653 					  complain & tf_error);
   20654 	else
   20655 	  r = cxx_sizeof_or_alignof_expr (input_location,
   20656 					  op1, TREE_CODE (t), std_alignof,
   20657 					  complain & tf_error);
   20658 	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
   20659 	  {
   20660 	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
   20661 	      {
   20662 		if (!processing_template_decl && TYPE_P (op1))
   20663 		  {
   20664 		    r = build_min (SIZEOF_EXPR, size_type_node,
   20665 				   build1 (NOP_EXPR, op1, error_mark_node));
   20666 		    SIZEOF_EXPR_TYPE_P (r) = 1;
   20667 		  }
   20668 		else
   20669 		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
   20670 		TREE_SIDE_EFFECTS (r) = 0;
   20671 		TREE_READONLY (r) = 1;
   20672 	      }
   20673 	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
   20674 	    copy_warning (r, t);
   20675 	  }
   20676 	RETURN (r);
   20677       }
   20678 
   20679     case AT_ENCODE_EXPR:
   20680       {
   20681 	op1 = TREE_OPERAND (t, 0);
   20682 	++cp_unevaluated_operand;
   20683 	++c_inhibit_evaluation_warnings;
   20684 	op1 = tsubst (op1, args, complain, in_decl);
   20685 	--cp_unevaluated_operand;
   20686 	--c_inhibit_evaluation_warnings;
   20687 	RETURN (objc_build_encode_expr (op1));
   20688       }
   20689 
   20690     case NOEXCEPT_EXPR:
   20691       op1 = TREE_OPERAND (t, 0);
   20692       ++cp_unevaluated_operand;
   20693       ++c_inhibit_evaluation_warnings;
   20694       ++cp_noexcept_operand;
   20695       op1 = tsubst_expr (op1, args, complain, in_decl);
   20696       --cp_unevaluated_operand;
   20697       --c_inhibit_evaluation_warnings;
   20698       --cp_noexcept_operand;
   20699       RETURN (finish_noexcept_expr (op1, complain));
   20700 
   20701     case MODOP_EXPR:
   20702       {
   20703 	warning_sentinel s(warn_div_by_zero);
   20704 	tree lhs = RECUR (TREE_OPERAND (t, 0));
   20705 	tree rhs = RECUR (TREE_OPERAND (t, 2));
   20706 
   20707 	tree r = build_x_modify_expr
   20708 	  (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
   20709 	   templated_operator_saved_lookups (t),
   20710 	   complain|decltype_flag);
   20711 	/* TREE_NO_WARNING must be set if either the expression was
   20712 	   parenthesized or it uses an operator such as >>= rather
   20713 	   than plain assignment.  In the former case, it was already
   20714 	   set and must be copied.  In the latter case,
   20715 	   build_x_modify_expr sets it and it must not be reset
   20716 	   here.  */
   20717 	if (warning_suppressed_p (t, OPT_Wparentheses))
   20718 	  suppress_warning (STRIP_REFERENCE_REF (r), OPT_Wparentheses);
   20719 
   20720 	RETURN (r);
   20721       }
   20722 
   20723     case ARROW_EXPR:
   20724       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
   20725 						args, complain, in_decl);
   20726       /* Remember that there was a reference to this entity.  */
   20727       if (DECL_P (op1)
   20728 	  && !mark_used (op1, complain) && !(complain & tf_error))
   20729 	RETURN (error_mark_node);
   20730       RETURN (build_x_arrow (input_location, op1, complain));
   20731 
   20732     case NEW_EXPR:
   20733       {
   20734 	tree placement = RECUR (TREE_OPERAND (t, 0));
   20735 	tree init = RECUR (TREE_OPERAND (t, 3));
   20736 	vec<tree, va_gc> *placement_vec;
   20737 	vec<tree, va_gc> *init_vec;
   20738 	tree ret;
   20739 	location_t loc = EXPR_LOCATION (t);
   20740 
   20741 	if (placement == NULL_TREE)
   20742 	  placement_vec = NULL;
   20743 	else if (placement == error_mark_node)
   20744 	  RETURN (error_mark_node);
   20745 	else
   20746 	  {
   20747 	    placement_vec = make_tree_vector ();
   20748 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
   20749 	      vec_safe_push (placement_vec, TREE_VALUE (placement));
   20750 	  }
   20751 
   20752 	/* If there was an initializer in the original tree, but it
   20753 	   instantiated to an empty list, then we should pass a
   20754 	   non-NULL empty vector to tell build_new that it was an
   20755 	   empty initializer() rather than no initializer.  This can
   20756 	   only happen when the initializer is a pack expansion whose
   20757 	   parameter packs are of length zero.  */
   20758 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
   20759 	  init_vec = NULL;
   20760 	else if (init == error_mark_node)
   20761 	  RETURN (error_mark_node);
   20762 	else
   20763 	  {
   20764 	    init_vec = make_tree_vector ();
   20765 	    if (init == void_node)
   20766 	      gcc_assert (init_vec != NULL);
   20767 	    else
   20768 	      {
   20769 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
   20770 		  vec_safe_push (init_vec, TREE_VALUE (init));
   20771 	      }
   20772 	  }
   20773 
   20774 	/* Avoid passing an enclosing decl to valid_array_size_p.  */
   20775 	in_decl = NULL_TREE;
   20776 
   20777 	tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
   20778 	tree op2 = RECUR (TREE_OPERAND (t, 2));
   20779 	ret = build_new (loc, &placement_vec, op1, op2,
   20780 			 &init_vec, NEW_EXPR_USE_GLOBAL (t),
   20781 			 complain);
   20782 
   20783 	if (placement_vec != NULL)
   20784 	  release_tree_vector (placement_vec);
   20785 	if (init_vec != NULL)
   20786 	  release_tree_vector (init_vec);
   20787 
   20788 	RETURN (ret);
   20789       }
   20790 
   20791     case DELETE_EXPR:
   20792       {
   20793 	tree op0 = RECUR (TREE_OPERAND (t, 0));
   20794 	tree op1 = RECUR (TREE_OPERAND (t, 1));
   20795 	RETURN (delete_sanity (input_location, op0, op1,
   20796 			       DELETE_EXPR_USE_VEC (t),
   20797 			       DELETE_EXPR_USE_GLOBAL (t),
   20798 			       complain));
   20799       }
   20800 
   20801     case COMPOUND_EXPR:
   20802       {
   20803 	tree op0 = tsubst_expr (TREE_OPERAND (t, 0), args,
   20804 				complain & ~tf_decltype, in_decl);
   20805 	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
   20806 				       op0,
   20807 				       RECUR (TREE_OPERAND (t, 1)),
   20808 				       templated_operator_saved_lookups (t),
   20809 				       complain|decltype_flag));
   20810       }
   20811 
   20812     case CALL_EXPR:
   20813       {
   20814 	tree function;
   20815 	unsigned int nargs;
   20816 	bool qualified_p;
   20817 	bool koenig_p;
   20818 	tree ret;
   20819 
   20820 	function = CALL_EXPR_FN (t);
   20821 	/* Internal function with no arguments.  */
   20822 	if (function == NULL_TREE && call_expr_nargs (t) == 0)
   20823 	  RETURN (t);
   20824 
   20825 	/* When we parsed the expression, we determined whether or
   20826 	   not Koenig lookup should be performed.  */
   20827 	koenig_p = KOENIG_LOOKUP_P (t);
   20828 	if (function == NULL_TREE)
   20829 	  {
   20830 	    koenig_p = false;
   20831 	    qualified_p = false;
   20832 	  }
   20833 	else if (TREE_CODE (function) == SCOPE_REF)
   20834 	  {
   20835 	    qualified_p = true;
   20836 	    function = tsubst_qualified_id (function, args, complain, in_decl,
   20837 					    /*done=*/false,
   20838 					    /*address_p=*/false);
   20839 	  }
   20840 	else if (CALL_EXPR_STATIC_CHAIN (t)
   20841 		 && TREE_CODE (function) == FUNCTION_DECL
   20842 		 && fndecl_built_in_p (function, BUILT_IN_CLASSIFY_TYPE))
   20843 	  {
   20844 	    tree type = tsubst (CALL_EXPR_STATIC_CHAIN (t), args, complain,
   20845 				in_decl);
   20846 	    if (dependent_type_p (type))
   20847 	      {
   20848 		ret = build_vl_exp (CALL_EXPR, 4);
   20849 		CALL_EXPR_FN (ret) = function;
   20850 		CALL_EXPR_STATIC_CHAIN (ret) = type;
   20851 		CALL_EXPR_ARG (ret, 0)
   20852 		  = build_min (SIZEOF_EXPR, size_type_node, type);
   20853 		TREE_TYPE (ret) = integer_type_node;
   20854 	      }
   20855 	    else
   20856 	      ret = build_int_cst (integer_type_node, type_to_class (type));
   20857 	    RETURN (ret);
   20858 	  }
   20859 	else if (koenig_p
   20860 		 && (identifier_p (function)
   20861 		     || (TREE_CODE (function) == TEMPLATE_ID_EXPR
   20862 			 && identifier_p (TREE_OPERAND (function, 0)))))
   20863 	  {
   20864 	    /* Do nothing; calling tsubst_expr on an identifier
   20865 	       would incorrectly perform unqualified lookup again.
   20866 
   20867 	       Note that we can also have an IDENTIFIER_NODE if the earlier
   20868 	       unqualified lookup found a dependent local extern declaration
   20869 	       (as per finish_call_expr); in that case koenig_p will be false
   20870 	       and we do want to do the lookup again to find the substituted
   20871 	       declaration.  */
   20872 	    qualified_p = false;
   20873 
   20874 	    if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
   20875 	      function = tsubst_name (function, args, complain, in_decl);
   20876 	  }
   20877 	else
   20878 	  {
   20879 	    if (TREE_CODE (function) == COMPONENT_REF)
   20880 	      {
   20881 		tree op = TREE_OPERAND (function, 1);
   20882 
   20883 		qualified_p = (TREE_CODE (op) == SCOPE_REF
   20884 			       || (BASELINK_P (op)
   20885 				   && BASELINK_QUALIFIED_P (op)));
   20886 	      }
   20887 	    else
   20888 	      qualified_p = false;
   20889 
   20890 	    if (TREE_CODE (function) == ADDR_EXPR
   20891 		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
   20892 	      /* Avoid error about taking the address of a constructor.  */
   20893 	      function = TREE_OPERAND (function, 0);
   20894 
   20895 	    tsubst_flags_t subcomplain = complain;
   20896 	    if (koenig_p && TREE_CODE (function) == FUNCTION_DECL)
   20897 	      /* When KOENIG_P, we don't want to mark_used the callee before
   20898 		 augmenting the overload set via ADL, so during this initial
   20899 		 substitution we disable mark_used by setting tf_conv (68942).  */
   20900 	      subcomplain |= tf_conv;
   20901 	    function = tsubst_expr (function, args, subcomplain, in_decl);
   20902 
   20903 	    if (BASELINK_P (function))
   20904 	      qualified_p = true;
   20905 	  }
   20906 
   20907 	nargs = call_expr_nargs (t);
   20908 	releasing_vec call_args;
   20909 	tsubst_call_args (t, args, complain, in_decl, call_args);
   20910 
   20911 	/* Stripped-down processing for a call in a thunk.  Specifically, in
   20912 	   the thunk template for a generic lambda.  */
   20913 	if (call_from_lambda_thunk_p (t))
   20914 	  {
   20915 	    /* Now that we've expanded any packs, the number of call args
   20916 	       might be different.  */
   20917 	    unsigned int cargs = call_args->length ();
   20918 	    tree thisarg = NULL_TREE;
   20919 	    if (TREE_CODE (function) == COMPONENT_REF)
   20920 	      {
   20921 		thisarg = TREE_OPERAND (function, 0);
   20922 		if (TREE_CODE (thisarg) == INDIRECT_REF)
   20923 		  thisarg = TREE_OPERAND (thisarg, 0);
   20924 		function = TREE_OPERAND (function, 1);
   20925 		if (TREE_CODE (function) == BASELINK)
   20926 		  function = BASELINK_FUNCTIONS (function);
   20927 	      }
   20928 	    /* We aren't going to do normal overload resolution, so force the
   20929 	       template-id to resolve.  */
   20930 	    function = resolve_nondeduced_context (function, complain);
   20931 	    for (unsigned i = 0; i < cargs; ++i)
   20932 	      {
   20933 		/* In a thunk, pass through args directly, without any
   20934 		   conversions.  */
   20935 		tree arg = (*call_args)[i];
   20936 		while (TREE_CODE (arg) != PARM_DECL)
   20937 		  arg = TREE_OPERAND (arg, 0);
   20938 		(*call_args)[i] = arg;
   20939 	      }
   20940 	    if (thisarg)
   20941 	      {
   20942 		/* If there are no other args, just push 'this'.  */
   20943 		if (cargs == 0)
   20944 		  vec_safe_push (call_args, thisarg);
   20945 		else
   20946 		  {
   20947 		    /* Otherwise, shift the other args over to make room.  */
   20948 		    tree last = (*call_args)[cargs - 1];
   20949 		    vec_safe_push (call_args, last);
   20950 		    for (int i = cargs - 1; i > 0; --i)
   20951 		      (*call_args)[i] = (*call_args)[i - 1];
   20952 		    (*call_args)[0] = thisarg;
   20953 		  }
   20954 	      }
   20955 	    ret = build_call_a (function, call_args->length (),
   20956 				call_args->address ());
   20957 	    /* The thunk location is not interesting.  */
   20958 	    SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
   20959 	    CALL_FROM_THUNK_P (ret) = true;
   20960 	    if (CLASS_TYPE_P (TREE_TYPE (ret)))
   20961 	      CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
   20962 
   20963 	    RETURN (ret);
   20964 	  }
   20965 
   20966 	/* We do not perform argument-dependent lookup if normal
   20967 	   lookup finds a non-function, in accordance with the
   20968 	   resolution of DR 218.  */
   20969 	if (koenig_p
   20970 	    && ((is_overloaded_fn (function)
   20971 		 /* If lookup found a member function, the Koenig lookup is
   20972 		    not appropriate, even if an unqualified-name was used
   20973 		    to denote the function.  */
   20974 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
   20975 		|| identifier_p (function)
   20976 		/* C++20 P0846: Lookup found nothing.  */
   20977 		|| (TREE_CODE (function) == TEMPLATE_ID_EXPR
   20978 		    && identifier_p (TREE_OPERAND (function, 0))))
   20979 	    /* Only do this when substitution turns a dependent call
   20980 	       into a non-dependent call.  */
   20981 	    && type_dependent_expression_p_push (t)
   20982 	    && !any_type_dependent_arguments_p (call_args))
   20983 	  function = perform_koenig_lookup (function, call_args, tf_none);
   20984 
   20985 	if (function != NULL_TREE
   20986 	    && (identifier_p (function)
   20987 		|| (TREE_CODE (function) == TEMPLATE_ID_EXPR
   20988 		    && identifier_p (TREE_OPERAND (function, 0))
   20989 		    && !any_dependent_template_arguments_p (TREE_OPERAND
   20990 							    (function, 1))))
   20991 	    && !any_type_dependent_arguments_p (call_args))
   20992 	  {
   20993 	    bool template_id_p = (TREE_CODE (function) == TEMPLATE_ID_EXPR);
   20994 	    if (template_id_p)
   20995 	      function = TREE_OPERAND (function, 0);
   20996 	    if (koenig_p && (complain & tf_warning_or_error))
   20997 	      {
   20998 		/* For backwards compatibility and good diagnostics, try
   20999 		   the unqualified lookup again if we aren't in SFINAE
   21000 		   context.  */
   21001 		tree unq = tsubst_expr (function, args, complain, in_decl);
   21002 		if (unq == error_mark_node)
   21003 		  RETURN (error_mark_node);
   21004 
   21005 		if (unq != function)
   21006 		  {
   21007 		    char const *const msg
   21008 		      = G_("%qD was not declared in this scope, "
   21009 			   "and no declarations were found by "
   21010 			   "argument-dependent lookup at the point "
   21011 			   "of instantiation");
   21012 
   21013 		    bool in_lambda = (current_class_type
   21014 				      && LAMBDA_TYPE_P (current_class_type));
   21015 		    /* In a lambda fn, we have to be careful to not
   21016 		       introduce new this captures.  Legacy code can't
   21017 		       be using lambdas anyway, so it's ok to be
   21018 		       stricter.  Be strict with C++20 template-id ADL too.
   21019 		       And be strict if we're already failing anyway.  */
   21020 		    bool strict = in_lambda || template_id_p || seen_error();
   21021 		    bool diag = true;
   21022 		    if (strict)
   21023 		      error_at (cp_expr_loc_or_input_loc (t),
   21024 				msg, function);
   21025 		    else
   21026 		      diag = permerror (cp_expr_loc_or_input_loc (t),
   21027 					msg, function);
   21028 		    if (diag)
   21029 		      {
   21030 			tree fn = unq;
   21031 
   21032 			if (INDIRECT_REF_P (fn))
   21033 			  fn = TREE_OPERAND (fn, 0);
   21034 			if (is_overloaded_fn (fn))
   21035 			  fn = get_first_fn (fn);
   21036 
   21037 			if (!DECL_P (fn))
   21038 			  /* Can't say anything more.  */;
   21039 			else if (DECL_CLASS_SCOPE_P (fn))
   21040 			  {
   21041 			    location_t loc = cp_expr_loc_or_input_loc (t);
   21042 			    inform (loc,
   21043 				    "declarations in dependent base %qT are "
   21044 				    "not found by unqualified lookup",
   21045 				    DECL_CLASS_CONTEXT (fn));
   21046 			    if (current_class_ptr)
   21047 			      inform (loc,
   21048 				      "use %<this->%D%> instead", function);
   21049 			    else
   21050 			      inform (loc,
   21051 				      "use %<%T::%D%> instead",
   21052 				      current_class_name, function);
   21053 			  }
   21054 			else
   21055 			  inform (DECL_SOURCE_LOCATION (fn),
   21056 				  "%qD declared here, later in the "
   21057 				  "translation unit", fn);
   21058 			if (strict)
   21059 			  RETURN (error_mark_node);
   21060 		      }
   21061 
   21062 		    function = unq;
   21063 		  }
   21064 	      }
   21065 	    if (identifier_p (function))
   21066 	      {
   21067 		if (complain & tf_error)
   21068 		  unqualified_name_lookup_error (function);
   21069 		RETURN (error_mark_node);
   21070 	      }
   21071 	  }
   21072 
   21073 	/* Remember that there was a reference to this entity.  */
   21074 	if (function != NULL_TREE
   21075 	    && DECL_P (function)
   21076 	    && !mark_used (function, complain) && !(complain & tf_error))
   21077 	  RETURN (error_mark_node);
   21078 
   21079 	if (!maybe_fold_fn_template_args (function, complain))
   21080 	  return error_mark_node;
   21081 
   21082 	/* Put back tf_decltype for the actual call.  */
   21083 	complain |= decltype_flag;
   21084 
   21085 	if (function == NULL_TREE)
   21086 	  switch (CALL_EXPR_IFN (t))
   21087 	    {
   21088 	    case IFN_LAUNDER:
   21089 	      gcc_assert (nargs == 1);
   21090 	      if (vec_safe_length (call_args) != 1)
   21091 		{
   21092 		  error_at (cp_expr_loc_or_input_loc (t),
   21093 			    "wrong number of arguments to "
   21094 			    "%<__builtin_launder%>");
   21095 		  ret = error_mark_node;
   21096 		}
   21097 	      else
   21098 		ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
   21099 					      (*call_args)[0], complain);
   21100 	      break;
   21101 
   21102 	    case IFN_VEC_CONVERT:
   21103 	      gcc_assert (nargs == 1);
   21104 	      if (vec_safe_length (call_args) != 1)
   21105 		{
   21106 		  error_at (cp_expr_loc_or_input_loc (t),
   21107 			    "wrong number of arguments to "
   21108 			    "%<__builtin_convertvector%>");
   21109 		  ret = error_mark_node;
   21110 		  break;
   21111 		}
   21112 	      ret = cp_build_vec_convert ((*call_args)[0], input_location,
   21113 					  tsubst (TREE_TYPE (t), args,
   21114 						  complain, in_decl),
   21115 					  complain);
   21116 	      if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
   21117 		RETURN (ret);
   21118 	      break;
   21119 
   21120 	    case IFN_SHUFFLEVECTOR:
   21121 	      {
   21122 		ret = build_x_shufflevector (input_location, call_args,
   21123 					     complain);
   21124 		if (ret != error_mark_node)
   21125 		  RETURN (ret);
   21126 		break;
   21127 	      }
   21128 
   21129 	    case IFN_ASSUME:
   21130 	      gcc_assert (nargs == 1);
   21131 	      if (vec_safe_length (call_args) != 1)
   21132 		{
   21133 		  error_at (cp_expr_loc_or_input_loc (t),
   21134 			    "wrong number of arguments to "
   21135 			    "%<assume%> attribute");
   21136 		  ret = error_mark_node;
   21137 		}
   21138 	      else
   21139 		{
   21140 		  tree &arg = (*call_args)[0];
   21141 		  if (!type_dependent_expression_p (arg))
   21142 		    arg = contextual_conv_bool (arg, tf_warning_or_error);
   21143 		  if (error_operand_p (arg))
   21144 		    {
   21145 		      ret = error_mark_node;
   21146 		      break;
   21147 		    }
   21148 		  ret = build_assume_call (EXPR_LOCATION (t), arg);
   21149 		  RETURN (ret);
   21150 		}
   21151 	      break;
   21152 
   21153 	    default:
   21154 	      /* Unsupported internal function with arguments.  */
   21155 	      gcc_unreachable ();
   21156 	    }
   21157 	else if (TREE_CODE (function) == OFFSET_REF
   21158 		 || TREE_CODE (function) == DOTSTAR_EXPR
   21159 		 || TREE_CODE (function) == MEMBER_REF)
   21160 	  ret = build_offset_ref_call_from_tree (function, &call_args,
   21161 						 complain);
   21162 	else if (concept_check_p (function))
   21163 	  {
   21164 	    /* FUNCTION is a template-id referring to a concept definition.  */
   21165 	    tree id = unpack_concept_check (function);
   21166 	    tree tmpl = TREE_OPERAND (id, 0);
   21167 	    tree args = TREE_OPERAND (id, 1);
   21168 
   21169 	    /* Calls to standard and variable concepts should have been
   21170 	       previously diagnosed.  */
   21171 	    gcc_assert (function_concept_p (tmpl));
   21172 
   21173 	    /* Ensure the result is wrapped as a call expression.  */
   21174 	    ret = build_concept_check (tmpl, args, tf_warning_or_error);
   21175 	  }
   21176 	else
   21177 	  ret = finish_call_expr (function, &call_args,
   21178 				  /*disallow_virtual=*/qualified_p,
   21179 				  koenig_p,
   21180 				  complain);
   21181 
   21182 	if (ret != error_mark_node)
   21183 	  {
   21184 	    bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
   21185 	    bool ord = CALL_EXPR_ORDERED_ARGS (t);
   21186 	    bool rev = CALL_EXPR_REVERSE_ARGS (t);
   21187 	    if (op || ord || rev)
   21188 	      if (tree call = extract_call_expr (ret))
   21189 		{
   21190 		  CALL_EXPR_OPERATOR_SYNTAX (call) = op;
   21191 		  CALL_EXPR_ORDERED_ARGS (call) = ord;
   21192 		  CALL_EXPR_REVERSE_ARGS (call) = rev;
   21193 		}
   21194 	    if (warning_suppressed_p (t, OPT_Wpessimizing_move))
   21195 	      /* This also suppresses -Wredundant-move.  */
   21196 	      suppress_warning (ret, OPT_Wpessimizing_move);
   21197 	  }
   21198 
   21199 	RETURN (ret);
   21200       }
   21201 
   21202     case COND_EXPR:
   21203       {
   21204 	tree cond = RECUR (TREE_OPERAND (t, 0));
   21205 	cond = mark_rvalue_use (cond);
   21206 	tree folded_cond = fold_non_dependent_expr (cond, complain);
   21207 	tree exp1, exp2;
   21208 
   21209 	if (TREE_CODE (folded_cond) == INTEGER_CST)
   21210 	  {
   21211 	    if (integer_zerop (folded_cond))
   21212 	      {
   21213 		++c_inhibit_evaluation_warnings;
   21214 		exp1 = RECUR (TREE_OPERAND (t, 1));
   21215 		--c_inhibit_evaluation_warnings;
   21216 		exp2 = RECUR (TREE_OPERAND (t, 2));
   21217 	      }
   21218 	    else
   21219 	      {
   21220 		exp1 = RECUR (TREE_OPERAND (t, 1));
   21221 		++c_inhibit_evaluation_warnings;
   21222 		exp2 = RECUR (TREE_OPERAND (t, 2));
   21223 		--c_inhibit_evaluation_warnings;
   21224 	      }
   21225 	    cond = folded_cond;
   21226 	  }
   21227 	else
   21228 	  {
   21229 	    exp1 = RECUR (TREE_OPERAND (t, 1));
   21230 	    exp2 = RECUR (TREE_OPERAND (t, 2));
   21231 	  }
   21232 
   21233 	warning_sentinel s(warn_duplicated_branches);
   21234 	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
   21235 					 cond, exp1, exp2, complain));
   21236       }
   21237 
   21238     case PSEUDO_DTOR_EXPR:
   21239       {
   21240 	tree op0 = RECUR (TREE_OPERAND (t, 0));
   21241 	tree op1 = RECUR (TREE_OPERAND (t, 1));
   21242 	tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
   21243 	RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
   21244 					       input_location));
   21245       }
   21246 
   21247     case TREE_LIST:
   21248       RETURN (tsubst_tree_list (t, args, complain, in_decl));
   21249 
   21250     case COMPONENT_REF:
   21251       {
   21252 	tree object;
   21253 	tree object_type;
   21254 	tree member;
   21255 	tree r;
   21256 
   21257 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
   21258 						     args, complain, in_decl);
   21259 	/* Remember that there was a reference to this entity.  */
   21260 	if (DECL_P (object)
   21261 	    && !mark_used (object, complain) && !(complain & tf_error))
   21262 	  RETURN (error_mark_node);
   21263 	object_type = TREE_TYPE (object);
   21264 
   21265 	member = TREE_OPERAND (t, 1);
   21266 	if (BASELINK_P (member))
   21267 	  member = tsubst_baselink (member,
   21268 				    non_reference (TREE_TYPE (object)),
   21269 				    args, complain, in_decl);
   21270 	else
   21271 	  member = tsubst_name (member, args, complain, in_decl);
   21272 	if (member == error_mark_node)
   21273 	  RETURN (error_mark_node);
   21274 
   21275 	if (object_type && TYPE_PTRMEMFUNC_P (object_type)
   21276 	    && TREE_CODE (member) == FIELD_DECL)
   21277 	  {
   21278 	    r = build_ptrmemfunc_access_expr (object, DECL_NAME (member));
   21279 	    RETURN (r);
   21280 	  }
   21281 	else if (TREE_CODE (member) == FIELD_DECL)
   21282 	  {
   21283 	    /* Assume access of this FIELD_DECL has already been checked; we
   21284 	       don't recheck it to avoid bogus access errors when substituting
   21285 	       a reduced constant initializer (97740).  */
   21286 	    gcc_checking_assert (TREE_CODE (TREE_OPERAND (t, 1)) == FIELD_DECL);
   21287 	    push_deferring_access_checks (dk_deferred);
   21288 	    r = finish_non_static_data_member (member, object, NULL_TREE,
   21289 					       complain);
   21290 	    pop_deferring_access_checks ();
   21291 	    if (REF_PARENTHESIZED_P (t))
   21292 	      r = force_paren_expr (r);
   21293 	    RETURN (r);
   21294 	  }
   21295 	else if (type_dependent_expression_p (object))
   21296 	  /* We can't do much here.  */;
   21297 	else if (!CLASS_TYPE_P (object_type))
   21298 	  {
   21299 	    if (scalarish_type_p (object_type))
   21300 	      {
   21301 		tree s = NULL_TREE;
   21302 		tree dtor = member;
   21303 
   21304 		if (TREE_CODE (dtor) == SCOPE_REF)
   21305 		  {
   21306 		    s = TREE_OPERAND (dtor, 0);
   21307 		    dtor = TREE_OPERAND (dtor, 1);
   21308 		  }
   21309 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
   21310 		  {
   21311 		    dtor = TREE_OPERAND (dtor, 0);
   21312 		    if (TYPE_P (dtor))
   21313 		      RETURN (finish_pseudo_destructor_expr
   21314 			      (object, s, dtor, input_location));
   21315 		  }
   21316 	      }
   21317 	  }
   21318 	else if (TREE_CODE (member) == SCOPE_REF
   21319 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
   21320 	  {
   21321 	    /* Lookup the template functions now that we know what the
   21322 	       scope is.  */
   21323 	    tree scope = TREE_OPERAND (member, 0);
   21324 	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
   21325 	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
   21326 	    member = lookup_qualified_name (scope, tmpl, LOOK_want::NORMAL,
   21327 					    /*complain=*/false);
   21328 	    if (BASELINK_P (member))
   21329 	      {
   21330 		BASELINK_FUNCTIONS (member)
   21331 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
   21332 			      args);
   21333 		member = (adjust_result_of_qualified_name_lookup
   21334 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
   21335 			   object_type));
   21336 	      }
   21337 	    else
   21338 	      {
   21339 		qualified_name_lookup_error (scope, tmpl, member,
   21340 					     input_location);
   21341 		RETURN (error_mark_node);
   21342 	      }
   21343 	  }
   21344 	else if (TREE_CODE (member) == SCOPE_REF
   21345 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
   21346 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
   21347 	  {
   21348 	    if (complain & tf_error)
   21349 	      {
   21350 		if (TYPE_P (TREE_OPERAND (member, 0)))
   21351 		  error ("%qT is not a class or namespace",
   21352 			 TREE_OPERAND (member, 0));
   21353 		else
   21354 		  error ("%qD is not a class or namespace",
   21355 			 TREE_OPERAND (member, 0));
   21356 	      }
   21357 	    RETURN (error_mark_node);
   21358 	  }
   21359 
   21360 	r = finish_class_member_access_expr (object, member,
   21361 					     /*template_p=*/false,
   21362 					     complain);
   21363 	if (REF_PARENTHESIZED_P (t))
   21364 	  r = force_paren_expr (r);
   21365 	RETURN (r);
   21366       }
   21367 
   21368     case THROW_EXPR:
   21369       RETURN (build_throw
   21370        (input_location, RECUR (TREE_OPERAND (t, 0)), complain));
   21371 
   21372     case CONSTRUCTOR:
   21373       {
   21374 	vec<constructor_elt, va_gc> *n;
   21375 	constructor_elt *ce;
   21376 	unsigned HOST_WIDE_INT idx;
   21377 	bool process_index_p;
   21378         int newlen;
   21379         bool need_copy_p = false;
   21380 	tree r;
   21381 
   21382 	tsubst_flags_t tcomplain = complain;
   21383 	if (COMPOUND_LITERAL_P (t))
   21384 	  tcomplain |= tf_tst_ok;
   21385 	tree type = tsubst (TREE_TYPE (t), args, tcomplain, in_decl);
   21386 	if (type == error_mark_node)
   21387 	  RETURN (error_mark_node);
   21388 
   21389 	/* We do not want to process the index of aggregate
   21390 	   initializers as they are identifier nodes which will be
   21391 	   looked up by digest_init.  */
   21392 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
   21393 
   21394 	if (null_member_pointer_value_p (t))
   21395 	  {
   21396 	    gcc_assert (same_type_p (type, TREE_TYPE (t)));
   21397 	    RETURN (t);
   21398 	  }
   21399 
   21400 	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
   21401         newlen = vec_safe_length (n);
   21402 	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
   21403 	  {
   21404 	    if (ce->index && process_index_p
   21405 		/* An identifier index is looked up in the type
   21406 		   being initialized, not the current scope.  */
   21407 		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
   21408 	      ce->index = RECUR (ce->index);
   21409 
   21410             if (PACK_EXPANSION_P (ce->value))
   21411               {
   21412                 /* Substitute into the pack expansion.  */
   21413                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
   21414                                                   in_decl);
   21415 
   21416 		if (ce->value == error_mark_node
   21417 		    || PACK_EXPANSION_P (ce->value))
   21418 		  ;
   21419 		else if (TREE_VEC_LENGTH (ce->value) == 1)
   21420                   /* Just move the argument into place.  */
   21421                   ce->value = TREE_VEC_ELT (ce->value, 0);
   21422                 else
   21423                   {
   21424                     /* Update the length of the final CONSTRUCTOR
   21425                        arguments vector, and note that we will need to
   21426                        copy.*/
   21427                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
   21428                     need_copy_p = true;
   21429                   }
   21430               }
   21431             else
   21432               ce->value = RECUR (ce->value);
   21433 	  }
   21434 
   21435         if (need_copy_p)
   21436           {
   21437             vec<constructor_elt, va_gc> *old_n = n;
   21438 
   21439             vec_alloc (n, newlen);
   21440             FOR_EACH_VEC_ELT (*old_n, idx, ce)
   21441               {
   21442                 if (TREE_CODE (ce->value) == TREE_VEC)
   21443                   {
   21444                     int i, len = TREE_VEC_LENGTH (ce->value);
   21445                     for (i = 0; i < len; ++i)
   21446                       CONSTRUCTOR_APPEND_ELT (n, 0,
   21447                                               TREE_VEC_ELT (ce->value, i));
   21448                   }
   21449                 else
   21450                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
   21451               }
   21452           }
   21453 
   21454 	r = build_constructor (init_list_type_node, n);
   21455 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
   21456 	CONSTRUCTOR_IS_DESIGNATED_INIT (r)
   21457 	  = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
   21458 
   21459 	if (TREE_HAS_CONSTRUCTOR (t))
   21460 	  {
   21461 	    fcl_t cl = fcl_functional;
   21462 	    if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
   21463 	      cl = fcl_c99;
   21464 	    RETURN (finish_compound_literal (type, r, complain, cl));
   21465 	  }
   21466 
   21467 	TREE_TYPE (r) = type;
   21468 	RETURN (r);
   21469       }
   21470 
   21471     case TYPEID_EXPR:
   21472       {
   21473 	tree operand_0 = TREE_OPERAND (t, 0);
   21474 	if (TYPE_P (operand_0))
   21475 	  {
   21476 	    operand_0 = tsubst (operand_0, args, complain, in_decl);
   21477 	    RETURN (get_typeid (operand_0, complain));
   21478 	  }
   21479 	else
   21480 	  {
   21481 	    operand_0 = RECUR (operand_0);
   21482 	    RETURN (build_typeid (operand_0, complain));
   21483 	  }
   21484       }
   21485 
   21486     case FUNCTION_DECL:
   21487     case PARM_DECL:
   21488     case VAR_DECL:
   21489       if (!args)
   21490 	RETURN (t);
   21491       tree r;
   21492       if (VAR_OR_FUNCTION_DECL_P (t)
   21493 	  && DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
   21494 	r = tsubst_decl (t, args, complain);
   21495       else if (VAR_OR_FUNCTION_DECL_P (t) && DECL_LOCAL_DECL_P (t))
   21496 	{
   21497 	  /* Local specialization will usually have been created when
   21498 	     we instantiated the DECL_EXPR_DECL. */
   21499 	  r = retrieve_local_specialization (t);
   21500 	  if (!r)
   21501 	    {
   21502 	      /* We're in a generic lambda referencing a local extern
   21503 		 from an outer block-scope of a non-template.  */
   21504 	      gcc_checking_assert (LAMBDA_FUNCTION_P (current_function_decl));
   21505 	      r = t;
   21506 	    }
   21507 	}
   21508       else if (local_variable_p (t)
   21509 	       && ((r = retrieve_local_specialization (t))
   21510 		   || TREE_CODE (t) == PARM_DECL
   21511 		   || uses_template_parms (DECL_CONTEXT (t))))
   21512 	{
   21513 	  if (r == NULL_TREE && TREE_CODE (t) == PARM_DECL)
   21514 	    {
   21515 	      /* We get here for a use of 'this' in an NSDMI.  */
   21516 	      if (DECL_NAME (t) == this_identifier && current_class_ptr)
   21517 		RETURN (current_class_ptr);
   21518 
   21519 	      /* This can happen for a parameter name used later in a function
   21520 		 declaration (such as in a late-specified return type).  Just
   21521 		 make a dummy decl, since it's only used for its type.  */
   21522 	      gcc_assert (cp_unevaluated_operand);
   21523 	      r = tsubst_decl (t, args, complain);
   21524 	      /* Give it the template pattern as its context; its true context
   21525 		 hasn't been instantiated yet and this is good enough for
   21526 		 mangling.  */
   21527 	      DECL_CONTEXT (r) = DECL_CONTEXT (t);
   21528 	    }
   21529 	  else if (r == NULL_TREE)
   21530 	    {
   21531 	      /* First try name lookup to find the instantiation.  */
   21532 	      r = lookup_name (DECL_NAME (t));
   21533 	      if (r)
   21534 		{
   21535 		  if (!VAR_P (r))
   21536 		    {
   21537 		      /* During error-recovery we may find a non-variable,
   21538 			 even an OVERLOAD: just bail out and avoid ICEs and
   21539 			 duplicate diagnostics (c++/62207).  */
   21540 		      gcc_assert (seen_error ());
   21541 		      RETURN (error_mark_node);
   21542 		    }
   21543 		  if (!is_capture_proxy (r))
   21544 		    {
   21545 		      /* Make sure the one we found is the one we want.  */
   21546 		      tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
   21547 		      if (ctx != DECL_CONTEXT (r))
   21548 			r = NULL_TREE;
   21549 		    }
   21550 		}
   21551 
   21552 	      if (r)
   21553 		/* OK */;
   21554 	      else
   21555 		{
   21556 		  /* This can happen for a variable used in a
   21557 		     late-specified return type of a local lambda, or for a
   21558 		     local static or constant.  Building a new VAR_DECL
   21559 		     should be OK in all those cases.  */
   21560 		  r = tsubst_decl (t, args, complain);
   21561 		  if (local_specializations)
   21562 		    /* Avoid infinite recursion (79640).  */
   21563 		    register_local_specialization (r, t);
   21564 		  if (decl_maybe_constant_var_p (r))
   21565 		    {
   21566 		      /* We can't call cp_finish_decl, so handle the
   21567 			 initializer by hand.  */
   21568 		      tree init = tsubst_init (DECL_INITIAL (t), r, args,
   21569 					       complain, in_decl);
   21570 		      if (!processing_template_decl)
   21571 			init = maybe_constant_init (init);
   21572 		      if (processing_template_decl
   21573 			  ? potential_constant_expression (init)
   21574 			  : reduced_constant_expression_p (init))
   21575 			DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
   21576 			  = TREE_CONSTANT (r) = true;
   21577 		      DECL_INITIAL (r) = init;
   21578 		      if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
   21579 			TREE_TYPE (r)
   21580 			  = do_auto_deduction (TREE_TYPE (r), init, auto_node,
   21581 					       complain, adc_variable_type);
   21582 		    }
   21583 		  gcc_assert (cp_unevaluated_operand
   21584 			      || processing_contract_condition
   21585 			      || TREE_STATIC (r)
   21586 			      || decl_constant_var_p (r)
   21587 			      || seen_error ());
   21588 		  if (!processing_template_decl
   21589 		      && !TREE_STATIC (r))
   21590 		    r = process_outer_var_ref (r, complain);
   21591 		}
   21592 	      /* Remember this for subsequent uses.  */
   21593 	      if (local_specializations)
   21594 		register_local_specialization (r, t);
   21595 	    }
   21596 	  if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
   21597 	    r = argument_pack_select_arg (r);
   21598 	}
   21599       else
   21600 	r = t;
   21601       if (!mark_used (r, complain))
   21602 	RETURN (error_mark_node);
   21603 
   21604       if (!no_name_lookup_flag
   21605 	  && (TREE_CODE (t) == PARM_DECL || TREE_CODE (t) == VAR_DECL))
   21606 	{
   21607 	  /* ??? We're doing a subset of finish_id_expression here.  */
   21608 	  if (tree wrap = maybe_get_tls_wrapper_call (r))
   21609 	    /* Replace an evaluated use of the thread_local variable with
   21610 	       a call to its wrapper.  */
   21611 	    r = wrap;
   21612 	  else if (outer_automatic_var_p (r))
   21613 	    r = process_outer_var_ref (r, complain);
   21614 
   21615 	  if (!TYPE_REF_P (TREE_TYPE (t)))
   21616 	    /* If the original type was a reference, we'll be wrapped in
   21617 	       the appropriate INDIRECT_REF.  */
   21618 	    r = convert_from_reference (r);
   21619 	}
   21620       RETURN (r);
   21621 
   21622     case CONST_DECL:
   21623       {
   21624 	tree enum_type;
   21625 	tree v;
   21626 
   21627 	if (DECL_TEMPLATE_PARM_P (t))
   21628 	  RETURN (RECUR (DECL_INITIAL (t)));
   21629 	if (!args || !uses_template_parms (DECL_CONTEXT (t)))
   21630 	  RETURN (t);
   21631 
   21632 	/* Unfortunately, we cannot just call lookup_name here.
   21633 	   Consider:
   21634 
   21635 	     template <int I> int f() {
   21636 	     enum E { a = I };
   21637 	     struct S { void g() { E e = a; } };
   21638 	     };
   21639 
   21640 	   When we instantiate f<7>::S::g(), say, lookup_name is not
   21641 	   clever enough to find f<7>::a.  */
   21642 	enum_type
   21643 	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
   21644 			      /*entering_scope=*/0);
   21645 
   21646 	for (v = TYPE_VALUES (enum_type);
   21647 	     v != NULL_TREE;
   21648 	     v = TREE_CHAIN (v))
   21649 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
   21650 	    RETURN (TREE_VALUE (v));
   21651 
   21652 	  /* We didn't find the name.  That should never happen; if
   21653 	     name-lookup found it during preliminary parsing, we
   21654 	     should find it again here during instantiation.  */
   21655 	gcc_unreachable ();
   21656 	RETURN (t);
   21657       }
   21658 
   21659     case FIELD_DECL:
   21660       if (DECL_CONTEXT (t))
   21661 	{
   21662 	  tree ctx;
   21663 
   21664 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
   21665 				  /*entering_scope=*/1);
   21666 	  if (ctx != DECL_CONTEXT (t))
   21667 	    {
   21668 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
   21669 	      if (!r)
   21670 		{
   21671 		  if (complain & tf_error)
   21672 		    error ("using invalid field %qD", t);
   21673 		  RETURN (error_mark_node);
   21674 		}
   21675 	      RETURN (r);
   21676 	    }
   21677 	}
   21678       RETURN (t);
   21679 
   21680     case NAMESPACE_DECL:
   21681     case OVERLOAD:
   21682       RETURN (t);
   21683 
   21684     case TEMPLATE_DECL:
   21685       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
   21686 	RETURN (tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
   21687 			args, complain, in_decl));
   21688       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
   21689 	RETURN (tsubst (t, args, complain, in_decl));
   21690       else if (DECL_CLASS_SCOPE_P (t)
   21691 	       && uses_template_parms (DECL_CONTEXT (t)))
   21692 	{
   21693 	  /* Template template argument like the following example need
   21694 	     special treatment:
   21695 
   21696 	       template <template <class> class TT> struct C {};
   21697 	       template <class T> struct D {
   21698 		 template <class U> struct E {};
   21699 		 C<E> c;				// #1
   21700 	       };
   21701 	       D<int> d;				// #2
   21702 
   21703 	     We are processing the template argument `E' in #1 for
   21704 	     the template instantiation #2.  Originally, `E' is a
   21705 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
   21706 	     have to substitute this with one having context `D<int>'.  */
   21707 
   21708 	  tree context = tsubst_aggr_type (DECL_CONTEXT (t), args, complain,
   21709 					   in_decl, /*entering_scope=*/true);
   21710 	  RETURN (lookup_field (context, DECL_NAME(t), 0, false));
   21711 	}
   21712       else
   21713 	/* Ordinary template template argument.  */
   21714 	RETURN (t);
   21715 
   21716     case TEMPLATE_PARM_INDEX:
   21717     case TYPE_DECL:
   21718       RETURN (tsubst (t, args, complain, in_decl));
   21719 
   21720     case CLEANUP_POINT_EXPR:
   21721       /* We shouldn't have built any of these during initial template
   21722 	 generation.  Instead, they should be built during instantiation
   21723 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
   21724       gcc_unreachable ();
   21725 
   21726     case OFFSET_REF:
   21727       {
   21728 	/* We should only get here for an OFFSET_REF like A::m; a .* in a
   21729 	   template is represented as a DOTSTAR_EXPR.  */
   21730 	gcc_checking_assert
   21731 	  (same_type_p (TREE_TYPE (t), TREE_TYPE (TREE_OPERAND (t, 1))));
   21732 	tree op0 = RECUR (TREE_OPERAND (t, 0));
   21733 	tree op1 = RECUR (TREE_OPERAND (t, 1));
   21734 	tree type = TREE_TYPE (op1);
   21735 	r = build2 (OFFSET_REF, type, op0, op1);
   21736 	PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
   21737 	if (!mark_used (op1, complain)
   21738 	    && !(complain & tf_error))
   21739 	  RETURN (error_mark_node);
   21740 	RETURN (r);
   21741       }
   21742 
   21743     case EXPR_PACK_EXPANSION:
   21744       error ("invalid use of pack expansion expression");
   21745       RETURN (error_mark_node);
   21746 
   21747     case NONTYPE_ARGUMENT_PACK:
   21748       error ("use %<...%> to expand argument pack");
   21749       RETURN (error_mark_node);
   21750 
   21751     case VOID_CST:
   21752       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
   21753       RETURN (t);
   21754 
   21755     case INTEGER_CST:
   21756     case REAL_CST:
   21757     case COMPLEX_CST:
   21758     case VECTOR_CST:
   21759       {
   21760 	/* Instantiate any typedefs in the type.  */
   21761 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   21762 	r = fold_convert (type, t);
   21763 	gcc_assert (TREE_CODE (r) == TREE_CODE (t));
   21764 	RETURN (r);
   21765       }
   21766 
   21767     case STRING_CST:
   21768       {
   21769 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   21770 	r = t;
   21771 	if (type != TREE_TYPE (t))
   21772 	  {
   21773 	    r = copy_node (t);
   21774 	    TREE_TYPE (r) = type;
   21775 	  }
   21776 	RETURN (r);
   21777       }
   21778 
   21779     case PTRMEM_CST:
   21780       /* These can sometimes show up in a partial instantiation, but never
   21781 	 involve template parms.  */
   21782       gcc_assert (!uses_template_parms (t));
   21783       RETURN (t);
   21784 
   21785     case UNARY_LEFT_FOLD_EXPR:
   21786       RETURN (tsubst_unary_left_fold (t, args, complain, in_decl));
   21787     case UNARY_RIGHT_FOLD_EXPR:
   21788       RETURN (tsubst_unary_right_fold (t, args, complain, in_decl));
   21789     case BINARY_LEFT_FOLD_EXPR:
   21790       RETURN (tsubst_binary_left_fold (t, args, complain, in_decl));
   21791     case BINARY_RIGHT_FOLD_EXPR:
   21792       RETURN (tsubst_binary_right_fold (t, args, complain, in_decl));
   21793     case PREDICT_EXPR:
   21794       RETURN (t);
   21795 
   21796     case DEBUG_BEGIN_STMT:
   21797       /* ??? There's no point in copying it for now, but maybe some
   21798 	 day it will contain more information, such as a pointer back
   21799 	 to the containing function, inlined copy or so.  */
   21800       RETURN (t);
   21801 
   21802     case CO_YIELD_EXPR:
   21803       RETURN (finish_co_yield_expr (input_location,
   21804 				    RECUR (TREE_OPERAND (t, 0))));
   21805 
   21806     case CO_AWAIT_EXPR:
   21807       RETURN (finish_co_await_expr (input_location,
   21808 				    RECUR (TREE_OPERAND (t, 0))));
   21809 
   21810     case VA_ARG_EXPR:
   21811       {
   21812 	tree op0 = RECUR (TREE_OPERAND (t, 0));
   21813 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   21814 	RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
   21815       }
   21816 
   21817     case OFFSETOF_EXPR:
   21818       {
   21819 	tree object_ptr
   21820 	  = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl);
   21821 	RETURN (finish_offsetof (object_ptr,
   21822 				 RECUR (TREE_OPERAND (t, 0)),
   21823 				 EXPR_LOCATION (t)));
   21824       }
   21825 
   21826     case ADDRESSOF_EXPR:
   21827       RETURN (cp_build_addressof (EXPR_LOCATION (t),
   21828 				  RECUR (TREE_OPERAND (t, 0)), complain));
   21829 
   21830     case TRAIT_EXPR:
   21831       {
   21832 	tree type1 = TRAIT_EXPR_TYPE1 (t);
   21833 	if (TYPE_P (type1))
   21834 	  type1 = tsubst (type1, args, complain, in_decl);
   21835 	else
   21836 	  type1 = tsubst_expr (type1, args, complain, in_decl);
   21837 	tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
   21838 			     complain, in_decl);
   21839 	RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
   21840 				   TRAIT_EXPR_KIND (t), type1, type2));
   21841       }
   21842 
   21843     case STMT_EXPR:
   21844       {
   21845 	tree old_stmt_expr = cur_stmt_expr;
   21846 	tree stmt_expr = begin_stmt_expr ();
   21847 
   21848 	cur_stmt_expr = stmt_expr;
   21849 	tsubst_stmt (STMT_EXPR_STMT (t), args, complain, in_decl);
   21850 	stmt_expr = finish_stmt_expr (stmt_expr, false);
   21851 	cur_stmt_expr = old_stmt_expr;
   21852 
   21853 	/* If the resulting list of expression statement is empty,
   21854 	   fold it further into void_node.  */
   21855 	if (empty_expr_stmt_p (stmt_expr))
   21856 	  stmt_expr = void_node;
   21857 
   21858 	RETURN (stmt_expr);
   21859       }
   21860 
   21861     case LAMBDA_EXPR:
   21862       {
   21863 	if (complain & tf_partial)
   21864 	  {
   21865 	    /* We don't have a full set of template arguments yet; don't touch
   21866 	       the lambda at all.  */
   21867 	    gcc_assert (processing_template_decl);
   21868 	    return t;
   21869 	  }
   21870 	tree r = tsubst_lambda_expr (t, args, complain, in_decl);
   21871 
   21872 	RETURN (build_lambda_object (r));
   21873       }
   21874 
   21875     case TRANSACTION_EXPR:
   21876       gcc_checking_assert (!TRANSACTION_EXPR_IS_STMT (t));
   21877       RETURN (tsubst_stmt (t, args, complain, in_decl));
   21878 
   21879     case PAREN_EXPR:
   21880       if (REF_PARENTHESIZED_P (t))
   21881 	RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
   21882       else
   21883 	/* Recreate the PAREN_EXPR from __builtin_assoc_barrier.  */
   21884 	{
   21885 	  tree op0 = RECUR (TREE_OPERAND (t, 0));
   21886 	  RETURN (build1_loc (input_location, PAREN_EXPR,
   21887 			      TREE_TYPE (op0), op0));
   21888 	}
   21889 
   21890     case VEC_PERM_EXPR:
   21891       {
   21892 	tree op0 = RECUR (TREE_OPERAND (t, 0));
   21893 	tree op1 = RECUR (TREE_OPERAND (t, 1));
   21894 	tree op2 = RECUR (TREE_OPERAND (t, 2));
   21895 	RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
   21896 				       complain));
   21897       }
   21898 
   21899     case REQUIRES_EXPR:
   21900       {
   21901 	complain &= ~tf_warning_or_error;
   21902 	tree r = tsubst_requires_expr (t, args, complain, in_decl);
   21903 	RETURN (r);
   21904       }
   21905 
   21906     case RANGE_EXPR:
   21907       /* No need to substitute further, a RANGE_EXPR will always be built
   21908 	 with constant operands.  */
   21909       RETURN (t);
   21910 
   21911     case NON_LVALUE_EXPR:
   21912     case VIEW_CONVERT_EXPR:
   21913       {
   21914 	tree op = RECUR (TREE_OPERAND (t, 0));
   21915 
   21916 	if (location_wrapper_p (t))
   21917 	  /* We need to do this here as well as in tsubst_copy so we get the
   21918 	     other tsubst_copy_and_build semantics for a PARM_DECL operand.  */
   21919 	  RETURN (maybe_wrap_with_location (op, EXPR_LOCATION (t)));
   21920 
   21921 	gcc_checking_assert (TREE_CODE (t) == VIEW_CONVERT_EXPR);
   21922 	if (REF_PARENTHESIZED_P (t))
   21923 	  /* force_paren_expr can also create a VIEW_CONVERT_EXPR.  */
   21924 	  RETURN (finish_parenthesized_expr (op));
   21925 
   21926 	/* Otherwise, we're dealing with a wrapper to make a C++20 template
   21927 	   parameter object const.  */
   21928 	if (TREE_TYPE (op) == NULL_TREE
   21929 	    || !CP_TYPE_CONST_P (TREE_TYPE (op)))
   21930 	  {
   21931 	    /* The template argument is not const, presumably because
   21932 	       it is still dependent, and so not the const template parm
   21933 	       object.  */
   21934 	    tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
   21935 	    if (TREE_CODE (op) == CONSTRUCTOR
   21936 		|| TREE_CODE (op) == IMPLICIT_CONV_EXPR)
   21937 	      {
   21938 		/* Don't add a wrapper to these.  */
   21939 		op = copy_node (op);
   21940 		TREE_TYPE (op) = type;
   21941 	      }
   21942 	    else
   21943 	      /* Do add a wrapper otherwise (in particular, if op is
   21944 		 another TEMPLATE_PARM_INDEX).  */
   21945 	      op = build1 (VIEW_CONVERT_EXPR, type, op);
   21946 	  }
   21947 	RETURN (op);
   21948       }
   21949 
   21950     default:
   21951       /* Handle Objective-C++ constructs, if appropriate.  */
   21952       if (tree subst = objcp_tsubst_expr (t, args, complain, in_decl))
   21953 	RETURN (subst);
   21954 
   21955       /* We shouldn't get here, but keep going if !flag_checking.  */
   21956       if (flag_checking)
   21957 	gcc_unreachable ();
   21958       RETURN (t);
   21959     }
   21960 
   21961 #undef RECUR
   21962 #undef RETURN
   21963  out:
   21964   input_location = save_loc;
   21965   return retval;
   21966 }
   21967 
   21968 /* Verify that the instantiated ARGS are valid. For type arguments,
   21969    make sure that the type's linkage is ok. For non-type arguments,
   21970    make sure they are constants if they are integral or enumerations.
   21971    Emit an error under control of COMPLAIN, and return TRUE on error.  */
   21972 
   21973 static bool
   21974 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
   21975 {
   21976   if (dependent_template_arg_p (t))
   21977     return false;
   21978   if (ARGUMENT_PACK_P (t))
   21979     {
   21980       tree vec = ARGUMENT_PACK_ARGS (t);
   21981       int len = TREE_VEC_LENGTH (vec);
   21982       bool result = false;
   21983       int i;
   21984 
   21985       for (i = 0; i < len; ++i)
   21986 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
   21987 	  result = true;
   21988       return result;
   21989     }
   21990   else if (TYPE_P (t))
   21991     {
   21992       /* [basic.link]: A name with no linkage (notably, the name
   21993 	 of a class or enumeration declared in a local scope)
   21994 	 shall not be used to declare an entity with linkage.
   21995 	 This implies that names with no linkage cannot be used as
   21996 	 template arguments
   21997 
   21998 	 DR 757 relaxes this restriction for C++0x.  */
   21999       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
   22000 		 : no_linkage_check (t, /*relaxed_p=*/false));
   22001 
   22002       if (nt)
   22003 	{
   22004 	  /* DR 488 makes use of a type with no linkage cause
   22005 	     type deduction to fail.  */
   22006 	  if (complain & tf_error)
   22007 	    {
   22008 	      if (TYPE_UNNAMED_P (nt))
   22009 		error ("%qT is/uses unnamed type", t);
   22010 	      else
   22011 		error ("template argument for %qD uses local type %qT",
   22012 		       tmpl, t);
   22013 	    }
   22014 	  return true;
   22015 	}
   22016       /* In order to avoid all sorts of complications, we do not
   22017 	 allow variably-modified types as template arguments.  */
   22018       else if (variably_modified_type_p (t, NULL_TREE))
   22019 	{
   22020 	  if (complain & tf_error)
   22021 	    error ("%qT is a variably modified type", t);
   22022 	  return true;
   22023 	}
   22024     }
   22025   /* Class template and alias template arguments should be OK.  */
   22026   else if (DECL_TYPE_TEMPLATE_P (t))
   22027     ;
   22028   /* A non-type argument of integral or enumerated type must be a
   22029      constant.  */
   22030   else if (TREE_TYPE (t)
   22031 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
   22032 	   && !REFERENCE_REF_P (t)
   22033 	   && !TREE_CONSTANT (t))
   22034     {
   22035       if (complain & tf_error)
   22036 	error ("integral expression %qE is not constant", t);
   22037       return true;
   22038     }
   22039   return false;
   22040 }
   22041 
   22042 static bool
   22043 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
   22044 {
   22045   int ix, len = DECL_NTPARMS (tmpl);
   22046   bool result = false;
   22047 
   22048   for (ix = 0; ix != len; ix++)
   22049     {
   22050       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
   22051 	result = true;
   22052     }
   22053   if (result && (complain & tf_error))
   22054     error ("  trying to instantiate %qD", tmpl);
   22055   return result;
   22056 }
   22057 
   22058 /* Call mark_used on each entity within the non-type template arguments in
   22059    ARGS for an instantiation of TMPL, to ensure that each such entity is
   22060    considered odr-used (and therefore marked for instantiation) regardless of
   22061    whether the specialization was first formed in a template context (which
   22062    inhibits mark_used).
   22063 
   22064    This function assumes push_to_top_level has been called beforehand.  */
   22065 
   22066 static void
   22067 mark_template_arguments_used (tree tmpl, tree args)
   22068 {
   22069   /* It suffices to do this only when instantiating a primary template.  */
   22070   if (TREE_CODE (tmpl) != TEMPLATE_DECL || !PRIMARY_TEMPLATE_P (tmpl))
   22071     return;
   22072 
   22073   /* We already marked outer arguments when specializing the context.  */
   22074   args = INNERMOST_TEMPLATE_ARGS (args);
   22075 
   22076   for (tree arg : tree_vec_range (args))
   22077     {
   22078       /* A (pointer/reference to) function or variable NTTP argument.  */
   22079       if (TREE_CODE (arg) == ADDR_EXPR
   22080 	  || TREE_CODE (arg) == INDIRECT_REF)
   22081 	{
   22082 	  while (TREE_CODE (arg) == ADDR_EXPR
   22083 		 || REFERENCE_REF_P (arg)
   22084 		 || CONVERT_EXPR_P (arg))
   22085 	    arg = TREE_OPERAND (arg, 0);
   22086 	  if (VAR_OR_FUNCTION_DECL_P (arg))
   22087 	    {
   22088 	      /* Pass tf_none to avoid duplicate diagnostics: if this call
   22089 		 fails then an earlier call to mark_used for this argument
   22090 		 must have also failed and emitted a diagnostic.  */
   22091 	      bool ok = mark_used (arg, tf_none);
   22092 	      gcc_checking_assert (ok || seen_error ());
   22093 	    }
   22094 	}
   22095       /* A member function pointer.  */
   22096       else if (TREE_CODE (arg) == PTRMEM_CST)
   22097 	{
   22098 	  bool ok = mark_used (PTRMEM_CST_MEMBER (arg), tf_none);
   22099 	  gcc_checking_assert (ok || seen_error ());
   22100 	}
   22101       /* A class NTTP argument.  */
   22102       else if (VAR_P (arg)
   22103 	       && DECL_NTTP_OBJECT_P (arg))
   22104 	{
   22105 	  auto mark_used_r = [](tree *tp, int *, void *) {
   22106 	    if (VAR_OR_FUNCTION_DECL_P (*tp))
   22107 	      {
   22108 		bool ok = mark_used (*tp, tf_none);
   22109 		gcc_checking_assert (ok || seen_error ());
   22110 	      }
   22111 	    return NULL_TREE;
   22112 	  };
   22113 	  cp_walk_tree_without_duplicates (&DECL_INITIAL (arg),
   22114 					   mark_used_r, nullptr);
   22115 	}
   22116     }
   22117 }
   22118 
   22119 /* We're out of SFINAE context now, so generate diagnostics for the access
   22120    errors we saw earlier when instantiating D from TMPL and ARGS.  */
   22121 
   22122 static void
   22123 recheck_decl_substitution (tree d, tree tmpl, tree args)
   22124 {
   22125   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
   22126   tree type = TREE_TYPE (pattern);
   22127   location_t loc = input_location;
   22128 
   22129   push_access_scope (d);
   22130   push_deferring_access_checks (dk_no_deferred);
   22131   input_location = DECL_SOURCE_LOCATION (pattern);
   22132   tsubst (type, args, tf_warning_or_error, d);
   22133   input_location = loc;
   22134   pop_deferring_access_checks ();
   22135   pop_access_scope (d);
   22136 }
   22137 
   22138 /* Instantiate the indicated variable, function, or alias template TMPL with
   22139    the template arguments in TARG_PTR.  */
   22140 
   22141 tree
   22142 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
   22143 {
   22144   auto_timevar tv (TV_TEMPLATE_INST);
   22145 
   22146   tree targ_ptr = orig_args;
   22147   tree fndecl;
   22148   tree gen_tmpl;
   22149   bool access_ok = true;
   22150 
   22151   if (tmpl == error_mark_node)
   22152     return error_mark_node;
   22153 
   22154   /* The other flags are not relevant anymore here, especially tf_partial
   22155      shouldn't be set.  For instance, we may be called while doing a partial
   22156      substitution of a template variable, but the type of the variable
   22157      template may be auto, in which case we will call do_auto_deduction
   22158      in mark_used (which clears tf_partial) and the auto must be properly
   22159      reduced at that time for the deduction to work.  */
   22160   complain &= tf_warning_or_error;
   22161 
   22162   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
   22163 
   22164   if (modules_p ())
   22165     lazy_load_pendings (tmpl);
   22166 
   22167   /* If this function is a clone, handle it specially.  */
   22168   if (DECL_CLONED_FUNCTION_P (tmpl))
   22169     {
   22170       tree spec;
   22171       tree clone;
   22172 
   22173       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
   22174 	 DECL_CLONED_FUNCTION.  */
   22175       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
   22176 				   targ_ptr, complain);
   22177       if (spec == error_mark_node)
   22178 	return error_mark_node;
   22179 
   22180       /* Look for the clone.  */
   22181       FOR_EACH_CLONE (clone, spec)
   22182 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
   22183 	  return clone;
   22184       /* We should always have found the clone by now.  */
   22185       gcc_unreachable ();
   22186       return NULL_TREE;
   22187     }
   22188 
   22189   if (targ_ptr == error_mark_node)
   22190     return error_mark_node;
   22191 
   22192   /* Check to see if we already have this specialization.  */
   22193   gen_tmpl = most_general_template (tmpl);
   22194   if (TMPL_ARGS_DEPTH (targ_ptr)
   22195       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
   22196     /* targ_ptr only has the innermost template args, so add the outer ones
   22197        from tmpl, which could be either a partial instantiation or gen_tmpl (in
   22198        the case of a non-dependent call within a template definition).  */
   22199     targ_ptr = (add_outermost_template_args
   22200 		(DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
   22201 		 targ_ptr));
   22202 
   22203   hashval_t hash = spec_hasher::hash (gen_tmpl, targ_ptr);
   22204   tree spec = retrieve_specialization (gen_tmpl, targ_ptr, hash);
   22205 
   22206   gcc_checking_assert (tmpl == gen_tmpl
   22207 		       || ((fndecl
   22208 			    = retrieve_specialization (tmpl, orig_args, 0))
   22209 			   == spec)
   22210 		       || fndecl == NULL_TREE);
   22211 
   22212   if (spec != NULL_TREE)
   22213     {
   22214       if (FNDECL_HAS_ACCESS_ERRORS (spec))
   22215 	{
   22216 	  if (complain & tf_error)
   22217 	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
   22218 	  return error_mark_node;
   22219 	}
   22220       return spec;
   22221     }
   22222 
   22223   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
   22224 			       complain))
   22225     return error_mark_node;
   22226 
   22227   /* We are building a FUNCTION_DECL, during which the access of its
   22228      parameters and return types have to be checked.  However this
   22229      FUNCTION_DECL which is the desired context for access checking
   22230      is not built yet.  We solve this chicken-and-egg problem by
   22231      deferring all checks until we have the FUNCTION_DECL.  */
   22232   push_deferring_access_checks (dk_deferred);
   22233 
   22234   /* Instantiation of the function happens in the context of the function
   22235      template, not the context of the overload resolution we're doing.  */
   22236   push_to_top_level ();
   22237   /* If there are dependent arguments, e.g. because we're doing partial
   22238      ordering, make sure processing_template_decl stays set.  */
   22239   if (uses_template_parms (targ_ptr))
   22240     ++processing_template_decl;
   22241   if (DECL_CLASS_SCOPE_P (gen_tmpl))
   22242     {
   22243       tree ctx;
   22244       if (!uses_template_parms (DECL_CONTEXT (tmpl)))
   22245 	/* If the context of the partially instantiated template is
   22246 	   already non-dependent, then we might as well use it.  */
   22247 	ctx = DECL_CONTEXT (tmpl);
   22248       else
   22249 	ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
   22250 				complain, gen_tmpl, true);
   22251       push_nested_class (ctx);
   22252     }
   22253 
   22254   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
   22255 
   22256   tree partial_ti = NULL_TREE;
   22257   fndecl = NULL_TREE;
   22258   if (VAR_P (pattern))
   22259     {
   22260       /* We need to determine if we're using a partial or explicit
   22261 	 specialization now, because the type of the variable could be
   22262 	 different.  */
   22263       tree tid = build2 (TEMPLATE_ID_EXPR, NULL_TREE, tmpl, targ_ptr);
   22264       partial_ti = most_specialized_partial_spec (tid, complain);
   22265       if (partial_ti == error_mark_node)
   22266 	pattern = error_mark_node;
   22267       else if (partial_ti)
   22268 	{
   22269 	  tree partial_tmpl = TI_TEMPLATE (partial_ti);
   22270 	  tree partial_args = TI_ARGS (partial_ti);
   22271 	  tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
   22272 	  fndecl = tsubst_decl (partial_pat, partial_args, complain,
   22273 				/*use_spec_table=*/false);
   22274 	}
   22275     }
   22276 
   22277   /* Substitute template parameters to obtain the specialization.  */
   22278   if (fndecl == NULL_TREE)
   22279     fndecl = tsubst_decl (pattern, targ_ptr, complain, /*use_spec_table=*/false);
   22280   if (DECL_CLASS_SCOPE_P (gen_tmpl))
   22281     pop_nested_class ();
   22282   pop_from_top_level ();
   22283 
   22284   if (fndecl == error_mark_node)
   22285     {
   22286       pop_deferring_access_checks ();
   22287       return error_mark_node;
   22288     }
   22289 
   22290   /* Substituting the type might have recursively instantiated this
   22291      same alias (c++/117530).  */
   22292   if (DECL_ALIAS_TEMPLATE_P (gen_tmpl)
   22293       && (spec = retrieve_specialization (gen_tmpl, targ_ptr, hash)))
   22294     {
   22295       pop_deferring_access_checks ();
   22296       return spec;
   22297     }
   22298 
   22299   /* The DECL_TI_TEMPLATE should always be the immediate parent
   22300      template, not the most general template.  */
   22301   DECL_TI_TEMPLATE (fndecl) = tmpl;
   22302   DECL_TI_ARGS (fndecl) = targ_ptr;
   22303   if (VAR_P (pattern))
   22304     {
   22305       /* Now that we we've formed this variable template specialization,
   22306 	 remember the result of most_specialized_partial_spec for it.  */
   22307       TI_PARTIAL_INFO (DECL_TEMPLATE_INFO (fndecl)) = partial_ti;
   22308 
   22309       /* And remember if the variable was declared with [].  */
   22310       if (TREE_CODE (TREE_TYPE (fndecl)) == ARRAY_TYPE
   22311 	  && TYPE_DOMAIN (TREE_TYPE (fndecl)) == NULL_TREE)
   22312 	SET_VAR_HAD_UNKNOWN_BOUND (fndecl);
   22313     }
   22314 
   22315   fndecl = register_specialization (fndecl, gen_tmpl, targ_ptr, false, hash);
   22316   if (fndecl == error_mark_node)
   22317     return error_mark_node;
   22318 
   22319   set_instantiating_module (fndecl);
   22320 
   22321   /* Now we know the specialization, compute access previously
   22322      deferred.  Do no access control for inheriting constructors,
   22323      as we already checked access for the inherited constructor.  */
   22324   if (!(flag_new_inheriting_ctors
   22325 	&& DECL_INHERITED_CTOR (fndecl)))
   22326     {
   22327       push_access_scope (fndecl);
   22328       if (!perform_deferred_access_checks (complain))
   22329 	access_ok = false;
   22330       pop_access_scope (fndecl);
   22331     }
   22332   pop_deferring_access_checks ();
   22333 
   22334   /* If we've just instantiated the main entry point for a function,
   22335      instantiate all the alternate entry points as well.  We do this
   22336      by cloning the instantiation of the main entry point, not by
   22337      instantiating the template clones.  */
   22338   if (tree chain = DECL_CHAIN (gen_tmpl))
   22339     if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
   22340       clone_cdtor (fndecl, /*update_methods=*/false);
   22341 
   22342   if (!access_ok)
   22343     {
   22344       if (!(complain & tf_error))
   22345 	{
   22346 	  /* Remember to reinstantiate when we're out of SFINAE so the user
   22347 	     can see the errors.  */
   22348 	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
   22349 	}
   22350       return error_mark_node;
   22351     }
   22352 
   22353   return fndecl;
   22354 }
   22355 
   22356 /* Instantiate the alias template TMPL with ARGS.  Also push a template
   22357    instantiation level, which instantiate_template doesn't do because
   22358    functions and variables have sufficient context established by the
   22359    callers.  */
   22360 
   22361 static tree
   22362 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
   22363 {
   22364   if (tmpl == error_mark_node || args == error_mark_node)
   22365     return error_mark_node;
   22366 
   22367   args = coerce_template_parms (DECL_TEMPLATE_PARMS (tmpl),
   22368 				args, tmpl, complain);
   22369   if (args == error_mark_node)
   22370     return error_mark_node;
   22371 
   22372   /* FIXME check for satisfaction in check_instantiated_args.  */
   22373   if (!constraints_satisfied_p (tmpl, args))
   22374     {
   22375       if (complain & tf_error)
   22376 	{
   22377 	  auto_diagnostic_group d;
   22378 	  error ("template constraint failure for %qD", tmpl);
   22379 	  diagnose_constraints (input_location, tmpl, args);
   22380 	}
   22381       return error_mark_node;
   22382     }
   22383 
   22384   if (!push_tinst_level (tmpl, args))
   22385     return error_mark_node;
   22386   tree r = instantiate_template (tmpl, args, complain);
   22387   pop_tinst_level ();
   22388 
   22389   if (tree d = dependent_alias_template_spec_p (TREE_TYPE (r), nt_opaque))
   22390     {
   22391       /* An alias template specialization can be dependent
   22392 	 even if its underlying type is not.  */
   22393       TYPE_DEPENDENT_P (d) = true;
   22394       TYPE_DEPENDENT_P_VALID (d) = true;
   22395       /* Sometimes a dependent alias spec is equivalent to its expansion,
   22396 	 sometimes not.  So always use structural_comptypes.  */
   22397       SET_TYPE_STRUCTURAL_EQUALITY (d);
   22398     }
   22399 
   22400   return r;
   22401 }
   22402 
   22403 /* PARM is a template parameter pack for FN.  Returns true iff
   22404    PARM is used in a deducible way in the argument list of FN.  */
   22405 
   22406 static bool
   22407 pack_deducible_p (tree parm, tree fn)
   22408 {
   22409   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
   22410   for (; t; t = TREE_CHAIN (t))
   22411     {
   22412       tree type = TREE_VALUE (t);
   22413       tree packs;
   22414       if (!PACK_EXPANSION_P (type))
   22415 	continue;
   22416       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
   22417 	   packs; packs = TREE_CHAIN (packs))
   22418 	if (template_args_equal (TREE_VALUE (packs), parm))
   22419 	  {
   22420 	    /* The template parameter pack is used in a function parameter
   22421 	       pack.  If this is the end of the parameter list, the
   22422 	       template parameter pack is deducible.  */
   22423 	    if (TREE_CHAIN (t) == void_list_node)
   22424 	      return true;
   22425 	    else
   22426 	      /* Otherwise, not.  Well, it could be deduced from
   22427 		 a non-pack parameter, but doing so would end up with
   22428 		 a deduction mismatch, so don't bother.  */
   22429 	      return false;
   22430 	  }
   22431     }
   22432   /* The template parameter pack isn't used in any function parameter
   22433      packs, but it might be used deeper, e.g. tuple<Args...>.  */
   22434   return true;
   22435 }
   22436 
   22437 /* Subroutine of fn_type_unification: check non-dependent parms for
   22438    convertibility.  */
   22439 
   22440 static int
   22441 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
   22442 				 tree fn, unification_kind_t strict, int flags,
   22443 				 struct conversion **convs, bool explain_p,
   22444 				 bool noninst_only_p)
   22445 {
   22446   /* Non-constructor methods need to leave a conversion for 'this', which
   22447      isn't included in nargs here.  */
   22448   unsigned offset = (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
   22449 		     && !DECL_CONSTRUCTOR_P (fn));
   22450 
   22451   for (unsigned ia = 0;
   22452        parms && parms != void_list_node && ia < nargs; )
   22453     {
   22454       tree parm = TREE_VALUE (parms);
   22455 
   22456       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
   22457 	  && (!TREE_CHAIN (parms)
   22458 	      || TREE_CHAIN (parms) == void_list_node))
   22459 	/* For a function parameter pack that occurs at the end of the
   22460 	   parameter-declaration-list, the type A of each remaining
   22461 	   argument of the call is compared with the type P of the
   22462 	   declarator-id of the function parameter pack.  */
   22463 	break;
   22464 
   22465       parms = TREE_CHAIN (parms);
   22466 
   22467       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
   22468 	/* For a function parameter pack that does not occur at the
   22469 	   end of the parameter-declaration-list, the type of the
   22470 	   parameter pack is a non-deduced context.  */
   22471 	continue;
   22472 
   22473       if (!uses_template_parms (parm))
   22474 	{
   22475 	  tree arg = args[ia];
   22476 	  conversion **conv_p = convs ? &convs[ia+offset] : NULL;
   22477 	  int lflags = conv_flags (ia, nargs, fn, arg, flags);
   22478 
   22479 	  if (check_non_deducible_conversion (parm, arg, strict, lflags,
   22480 					      conv_p, explain_p, noninst_only_p))
   22481 	    return 1;
   22482 	}
   22483 
   22484       ++ia;
   22485     }
   22486 
   22487   return 0;
   22488 }
   22489 
   22490 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
   22491    NARGS elements of the arguments that are being used when calling
   22492    it.  TARGS is a vector into which the deduced template arguments
   22493    are placed.
   22494 
   22495    Returns either a FUNCTION_DECL for the matching specialization of FN or
   22496    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
   22497    true, diagnostics will be printed to explain why it failed.
   22498 
   22499    If FN is a conversion operator, or we are trying to produce a specific
   22500    specialization, RETURN_TYPE is the return type desired.
   22501 
   22502    The EXPLICIT_TARGS are explicit template arguments provided via a
   22503    template-id.
   22504 
   22505    The parameter STRICT is one of:
   22506 
   22507    DEDUCE_CALL:
   22508      We are deducing arguments for a function call, as in
   22509      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
   22510      deducing arguments for a call to the result of a conversion
   22511      function template, as in [over.call.object].
   22512 
   22513    DEDUCE_CONV:
   22514      We are deducing arguments for a conversion function, as in
   22515      [temp.deduct.conv].
   22516 
   22517    DEDUCE_EXACT:
   22518      We are deducing arguments when doing an explicit instantiation
   22519      as in [temp.explicit], when determining an explicit specialization
   22520      as in [temp.expl.spec], or when taking the address of a function
   22521      template, as in [temp.deduct.funcaddr].  */
   22522 
   22523 tree
   22524 fn_type_unification (tree fn,
   22525 		     tree explicit_targs,
   22526 		     tree targs,
   22527 		     const tree *args,
   22528 		     unsigned int nargs,
   22529 		     tree return_type,
   22530 		     unification_kind_t strict,
   22531 		     int flags,
   22532 		     struct conversion **convs,
   22533 		     bool explain_p,
   22534 		     bool decltype_p)
   22535 {
   22536   tree parms;
   22537   tree fntype;
   22538   tree decl = NULL_TREE;
   22539   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
   22540   bool ok;
   22541   static int deduction_depth;
   22542   /* type_unification_real will pass back any access checks from default
   22543      template argument substitution.  */
   22544   vec<deferred_access_check, va_gc> *checks = NULL;
   22545   /* We don't have all the template args yet.  */
   22546   bool incomplete = true;
   22547 
   22548   tree orig_fn = fn;
   22549   if (flag_new_inheriting_ctors)
   22550     fn = strip_inheriting_ctors (fn);
   22551 
   22552   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
   22553   tree r = error_mark_node;
   22554 
   22555   tree full_targs = targs;
   22556   if (TMPL_ARGS_DEPTH (targs)
   22557       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
   22558     full_targs = (add_outermost_template_args
   22559 		  (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
   22560 		   targs));
   22561 
   22562   if (decltype_p)
   22563     complain |= tf_decltype;
   22564 
   22565   /* In C++0x, it's possible to have a function template whose type depends
   22566      on itself recursively.  This is most obvious with decltype, but can also
   22567      occur with enumeration scope (c++/48969).  So we need to catch infinite
   22568      recursion and reject the substitution at deduction time; this function
   22569      will return error_mark_node for any repeated substitution.
   22570 
   22571      This also catches excessive recursion such as when f<N> depends on
   22572      f<N-1> across all integers, and returns error_mark_node for all the
   22573      substitutions back up to the initial one.
   22574 
   22575      This is, of course, not reentrant.  */
   22576   if (excessive_deduction_depth)
   22577     return error_mark_node;
   22578   ++deduction_depth;
   22579 
   22580   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
   22581 
   22582   fntype = TREE_TYPE (fn);
   22583   if (explicit_targs)
   22584     {
   22585       /* [temp.deduct]
   22586 
   22587 	 The specified template arguments must match the template
   22588 	 parameters in kind (i.e., type, nontype, template), and there
   22589 	 must not be more arguments than there are parameters;
   22590 	 otherwise type deduction fails.
   22591 
   22592 	 Nontype arguments must match the types of the corresponding
   22593 	 nontype template parameters, or must be convertible to the
   22594 	 types of the corresponding nontype parameters as specified in
   22595 	 _temp.arg.nontype_, otherwise type deduction fails.
   22596 
   22597 	 All references in the function type of the function template
   22598 	 to the corresponding template parameters are replaced by the
   22599 	 specified template argument values.  If a substitution in a
   22600 	 template parameter or in the function type of the function
   22601 	 template results in an invalid type, type deduction fails.  */
   22602       int i, len = TREE_VEC_LENGTH (tparms);
   22603       location_t loc = input_location;
   22604       incomplete = false;
   22605 
   22606       if (explicit_targs == error_mark_node)
   22607 	goto fail;
   22608 
   22609       if (TMPL_ARGS_DEPTH (explicit_targs)
   22610 	  < TMPL_ARGS_DEPTH (full_targs))
   22611 	explicit_targs = add_outermost_template_args (full_targs,
   22612 						      explicit_targs);
   22613 
   22614       /* Adjust any explicit template arguments before entering the
   22615 	 substitution context.  */
   22616       explicit_targs
   22617 	= (coerce_template_parms (tparms, explicit_targs, fn,
   22618 				  complain|tf_partial,
   22619 				  /*require_all_args=*/false));
   22620       if (explicit_targs == error_mark_node)
   22621 	goto fail;
   22622 
   22623       /* Substitute the explicit args into the function type.  This is
   22624 	 necessary so that, for instance, explicitly declared function
   22625 	 arguments can match null pointed constants.  If we were given
   22626 	 an incomplete set of explicit args, we must not do semantic
   22627 	 processing during substitution as we could create partial
   22628 	 instantiations.  */
   22629       for (i = 0; i < len; i++)
   22630         {
   22631           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
   22632           bool parameter_pack = false;
   22633 	  tree targ = TREE_VEC_ELT (explicit_targs, i);
   22634 
   22635           /* Dig out the actual parm.  */
   22636           if (TREE_CODE (parm) == TYPE_DECL
   22637               || TREE_CODE (parm) == TEMPLATE_DECL)
   22638             {
   22639               parm = TREE_TYPE (parm);
   22640               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
   22641             }
   22642           else if (TREE_CODE (parm) == PARM_DECL)
   22643             {
   22644               parm = DECL_INITIAL (parm);
   22645               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
   22646             }
   22647 
   22648 	  if (targ == NULL_TREE)
   22649 	    /* No explicit argument for this template parameter.  */
   22650 	    incomplete = true;
   22651 	  else if (parameter_pack && pack_deducible_p (parm, fn))
   22652             {
   22653               /* Mark the argument pack as "incomplete". We could
   22654                  still deduce more arguments during unification.
   22655 	         We remove this mark in type_unification_real.  */
   22656 	      ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
   22657 	      ARGUMENT_PACK_EXPLICIT_ARGS (targ)
   22658 		= ARGUMENT_PACK_ARGS (targ);
   22659 
   22660               /* We have some incomplete argument packs.  */
   22661               incomplete = true;
   22662             }
   22663         }
   22664 
   22665       if (incomplete)
   22666 	{
   22667 	  if (!push_tinst_level (fn, explicit_targs))
   22668 	    {
   22669 	      excessive_deduction_depth = true;
   22670 	      goto fail;
   22671 	    }
   22672 	  ++processing_template_decl;
   22673 	  input_location = DECL_SOURCE_LOCATION (fn);
   22674 	  /* Ignore any access checks; we'll see them again in
   22675 	     instantiate_template and they might have the wrong
   22676 	     access path at this point.  */
   22677 	  push_deferring_access_checks (dk_deferred);
   22678 	  tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
   22679 	  fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
   22680 	  pop_deferring_access_checks ();
   22681 	  input_location = loc;
   22682 	  --processing_template_decl;
   22683 	  pop_tinst_level ();
   22684 
   22685 	  if (fntype == error_mark_node)
   22686 	    goto fail;
   22687 	}
   22688 
   22689       /* Place the explicitly specified arguments in TARGS.  */
   22690       explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
   22691       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
   22692 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
   22693       if (!incomplete && CHECKING_P
   22694 	  && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
   22695 	SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
   22696 	  (targs, NUM_TMPL_ARGS (explicit_targs));
   22697     }
   22698 
   22699   if (return_type && strict != DEDUCE_CALL)
   22700     {
   22701       tree *new_args = XALLOCAVEC (tree, nargs + 1);
   22702       new_args[0] = return_type;
   22703       memcpy (new_args + 1, args, nargs * sizeof (tree));
   22704       args = new_args;
   22705       ++nargs;
   22706     }
   22707 
   22708   if (!incomplete)
   22709     goto deduced;
   22710 
   22711   /* Never do unification on the 'this' parameter.  */
   22712   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
   22713 
   22714   if (return_type && strict == DEDUCE_CALL)
   22715     {
   22716       /* We're deducing for a call to the result of a template conversion
   22717          function.  The parms we really want are in return_type.  */
   22718       if (INDIRECT_TYPE_P (return_type))
   22719 	return_type = TREE_TYPE (return_type);
   22720       parms = TYPE_ARG_TYPES (return_type);
   22721     }
   22722   else if (return_type)
   22723     {
   22724       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
   22725     }
   22726 
   22727   /* We allow incomplete unification without an error message here
   22728      because the standard doesn't seem to explicitly prohibit it.  Our
   22729      callers must be ready to deal with unification failures in any
   22730      event.  */
   22731 
   22732   /* If we aren't explaining yet, push tinst context so we can see where
   22733      any errors (e.g. from class instantiations triggered by instantiation
   22734      of default template arguments) come from.  If we are explaining, this
   22735      context is redundant.  */
   22736   if (!explain_p && !push_tinst_level (fn, targs))
   22737     {
   22738       excessive_deduction_depth = true;
   22739       goto fail;
   22740     }
   22741 
   22742   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
   22743 			       full_targs, parms, args, nargs, /*subr=*/0,
   22744 			       strict, &checks, explain_p);
   22745   if (!explain_p)
   22746     pop_tinst_level ();
   22747   if (!ok)
   22748     goto fail;
   22749 
   22750   /* Now that we have bindings for all of the template arguments,
   22751      ensure that the arguments deduced for the template template
   22752      parameters have compatible template parameter lists.  We cannot
   22753      check this property before we have deduced all template
   22754      arguments, because the template parameter types of a template
   22755      template parameter might depend on prior template parameters
   22756      deduced after the template template parameter.  The following
   22757      ill-formed example illustrates this issue:
   22758 
   22759        template<typename T, template<T> class C> void f(C<5>, T);
   22760 
   22761        template<int N> struct X {};
   22762 
   22763        void g() {
   22764          f(X<5>(), 5l); // error: template argument deduction fails
   22765        }
   22766 
   22767      The template parameter list of 'C' depends on the template type
   22768      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
   22769      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
   22770      time that we deduce 'C'.  */
   22771   if (!template_template_parm_bindings_ok_p
   22772            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
   22773     {
   22774       unify_inconsistent_template_template_parameters (explain_p);
   22775       goto fail;
   22776     }
   22777 
   22778  deduced:
   22779 
   22780   /* As a refinement of CWG2369, check first and foremost non-dependent
   22781      conversions that we know are not going to induce template instantiation
   22782      (PR99599).  */
   22783   if (strict == DEDUCE_CALL
   22784       && incomplete
   22785       && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
   22786 					  convs, explain_p,
   22787 					  /*noninst_only_p=*/true))
   22788     goto fail;
   22789 
   22790   /* CWG2369: Check satisfaction before non-deducible conversions.  */
   22791   if (!constraints_satisfied_p (fn, targs))
   22792     {
   22793       if (explain_p)
   22794 	diagnose_constraints (DECL_SOURCE_LOCATION (fn), fn, targs);
   22795       goto fail;
   22796     }
   22797 
   22798   /* DR 1391: All parameters have args, now check non-dependent parms for
   22799      convertibility.  We don't do this if all args were explicitly specified,
   22800      as the standard says that we substitute explicit args immediately.  */
   22801   if (incomplete
   22802       && check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
   22803 					  convs, explain_p,
   22804 					  /*noninst_only_p=*/false))
   22805     goto fail;
   22806 
   22807   /* All is well so far.  Now, check:
   22808 
   22809      [temp.deduct]
   22810 
   22811      When all template arguments have been deduced, all uses of
   22812      template parameters in nondeduced contexts are replaced with
   22813      the corresponding deduced argument values.  If the
   22814      substitution results in an invalid type, as described above,
   22815      type deduction fails.  */
   22816   if (!push_tinst_level (fn, targs))
   22817     {
   22818       excessive_deduction_depth = true;
   22819       goto fail;
   22820     }
   22821 
   22822   /* Also collect access checks from the instantiation.  */
   22823   reopen_deferring_access_checks (checks);
   22824 
   22825   decl = instantiate_template (fn, targs, complain);
   22826 
   22827   checks = get_deferred_access_checks ();
   22828   pop_deferring_access_checks ();
   22829 
   22830   pop_tinst_level ();
   22831 
   22832   if (decl == error_mark_node)
   22833     goto fail;
   22834 
   22835   /* Now perform any access checks encountered during substitution.  */
   22836   push_access_scope (decl);
   22837   ok = perform_access_checks (checks, complain);
   22838   pop_access_scope (decl);
   22839   if (!ok)
   22840     goto fail;
   22841 
   22842   /* If we're looking for an exact match, check that what we got
   22843      is indeed an exact match.  It might not be if some template
   22844      parameters are used in non-deduced contexts.  But don't check
   22845      for an exact match if we have dependent template arguments;
   22846      in that case we're doing partial ordering, and we already know
   22847      that we have two candidates that will provide the actual type.  */
   22848   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
   22849     {
   22850       tree substed = TREE_TYPE (decl);
   22851       unsigned int i;
   22852 
   22853       tree sarg
   22854 	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
   22855       if (return_type)
   22856 	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
   22857       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
   22858 	if (!same_type_p (args[i], TREE_VALUE (sarg)))
   22859 	  {
   22860 	    unify_type_mismatch (explain_p, args[i],
   22861 				 TREE_VALUE (sarg));
   22862 	    goto fail;
   22863 	  }
   22864       if ((i < nargs || sarg)
   22865 	  /* add_candidates uses DEDUCE_EXACT for x.operator foo(), but args
   22866 	     doesn't contain the trailing void, and conv fns are always ().  */
   22867 	  && !DECL_CONV_FN_P (decl))
   22868 	{
   22869 	  unsigned nsargs = i + list_length (sarg);
   22870 	  unify_arity (explain_p, nargs, nsargs);
   22871 	  goto fail;
   22872 	}
   22873     }
   22874 
   22875   /* After doing deduction with the inherited constructor, actually return an
   22876      instantiation of the inheriting constructor.  */
   22877   if (orig_fn != fn)
   22878     decl = instantiate_template (orig_fn, targs, complain);
   22879 
   22880   r = decl;
   22881 
   22882  fail:
   22883   --deduction_depth;
   22884   if (excessive_deduction_depth)
   22885     {
   22886       if (deduction_depth == 0)
   22887 	/* Reset once we're all the way out.  */
   22888 	excessive_deduction_depth = false;
   22889     }
   22890 
   22891   return r;
   22892 }
   22893 
   22894 /* Returns true iff PARM is a forwarding reference in the context of
   22895    template argument deduction for TMPL.  */
   22896 
   22897 static bool
   22898 forwarding_reference_p (tree parm, tree tmpl)
   22899 {
   22900   /* [temp.deduct.call], "A forwarding reference is an rvalue reference to a
   22901      cv-unqualified template parameter ..."  */
   22902   if (TYPE_REF_P (parm)
   22903       && TYPE_REF_IS_RVALUE (parm)
   22904       && TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM
   22905       && cp_type_quals (TREE_TYPE (parm)) == TYPE_UNQUALIFIED)
   22906     {
   22907       parm = TREE_TYPE (parm);
   22908       /* [temp.deduct.call], "... that does not represent a template parameter
   22909 	 of a class template (during class template argument deduction)."  */
   22910       if (tmpl
   22911 	  && deduction_guide_p (tmpl)
   22912 	  && DECL_ARTIFICIAL (tmpl))
   22913 	{
   22914 	  /* Since the template parameters of a synthesized guide consist of
   22915 	     the template parameters of the class template followed by those of
   22916 	     the constructor (if any), we can tell if PARM represents a template
   22917 	     parameter of the class template by comparing its index with the
   22918 	     arity of the class template.  */
   22919 	  tree ctmpl = CLASSTYPE_TI_TEMPLATE (TREE_TYPE (TREE_TYPE (tmpl)));
   22920 	  if (TEMPLATE_TYPE_IDX (parm)
   22921 	      < TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (ctmpl)))
   22922 	    return false;
   22923 	}
   22924       return true;
   22925     }
   22926   return false;
   22927 }
   22928 
   22929 /* Adjust types before performing type deduction, as described in
   22930    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
   22931    sections are symmetric.  PARM is the type of a function parameter
   22932    or the return type of the conversion function.  ARG is the type of
   22933    the argument passed to the call, or the type of the value
   22934    initialized with the result of the conversion function.
   22935    ARG_EXPR is the original argument expression, which may be null.  */
   22936 
   22937 static int
   22938 maybe_adjust_types_for_deduction (tree tparms,
   22939 				  unification_kind_t strict,
   22940 				  tree* parm,
   22941 				  tree* arg,
   22942 				  tree arg_expr)
   22943 {
   22944   int result = 0;
   22945 
   22946   switch (strict)
   22947     {
   22948     case DEDUCE_CALL:
   22949       break;
   22950 
   22951     case DEDUCE_CONV:
   22952       /* [temp.deduct.conv] First remove a reference type on parm.
   22953 	 DRs 322 & 976 affected this.  */
   22954       if (TYPE_REF_P (*parm))
   22955 	*parm = TREE_TYPE (*parm);
   22956 
   22957       /* Swap PARM and ARG throughout the remainder of this
   22958 	 function; the handling is precisely symmetric since PARM
   22959 	 will initialize ARG rather than vice versa.  */
   22960       std::swap (parm, arg);
   22961 
   22962       break;
   22963 
   22964     case DEDUCE_EXACT:
   22965       /* Core issue #873: Do the DR606 thing (see below) for these cases,
   22966 	 too, but here handle it by stripping the reference from PARM
   22967 	 rather than by adding it to ARG.  */
   22968       if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
   22969 	  && TYPE_REF_P (*arg)
   22970 	  && !TYPE_REF_IS_RVALUE (*arg))
   22971 	*parm = TREE_TYPE (*parm);
   22972       /* Nothing else to do in this case.  */
   22973       return 0;
   22974 
   22975     default:
   22976       gcc_unreachable ();
   22977     }
   22978 
   22979   if (!TYPE_REF_P (*parm))
   22980     {
   22981       /* [temp.deduct.call]
   22982 
   22983 	 If P is not a reference type:
   22984 
   22985 	 --If A is an array type, the pointer type produced by the
   22986 	 array-to-pointer standard conversion (_conv.array_) is
   22987 	 used in place of A for type deduction; otherwise,
   22988 
   22989 	 --If A is a function type, the pointer type produced by
   22990 	 the function-to-pointer standard conversion
   22991 	 (_conv.func_) is used in place of A for type deduction;
   22992 	 otherwise,
   22993 
   22994 	 --If A is a cv-qualified type, the top level
   22995 	 cv-qualifiers of A's type are ignored for type
   22996 	 deduction.  */
   22997       if (TREE_CODE (*arg) == ARRAY_TYPE)
   22998 	*arg = build_pointer_type (TREE_TYPE (*arg));
   22999       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
   23000 	*arg = build_pointer_type (*arg);
   23001       else
   23002 	*arg = TYPE_MAIN_VARIANT (*arg);
   23003     }
   23004 
   23005   /* [temp.deduct.call], "If P is a forwarding reference and the argument is
   23006      an lvalue, the type 'lvalue reference to A' is used in place of A for
   23007      type deduction."  */
   23008   if (forwarding_reference_p (*parm, TPARMS_PRIMARY_TEMPLATE (tparms))
   23009       && (arg_expr ? lvalue_p (arg_expr)
   23010 	  /* try_one_overload doesn't provide an arg_expr, but
   23011 	     functions are always lvalues.  */
   23012 	  : TREE_CODE (*arg) == FUNCTION_TYPE))
   23013     *arg = build_reference_type (*arg);
   23014 
   23015   /* [temp.deduct.call]
   23016 
   23017      If P is a cv-qualified type, the top level cv-qualifiers
   23018      of P's type are ignored for type deduction.  If P is a
   23019      reference type, the type referred to by P is used for
   23020      type deduction.  */
   23021   *parm = TYPE_MAIN_VARIANT (*parm);
   23022   if (TYPE_REF_P (*parm))
   23023     {
   23024       *parm = TREE_TYPE (*parm);
   23025       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
   23026     }
   23027 
   23028   return result;
   23029 }
   23030 
   23031 /* Return true if computing a conversion from FROM to TO might induce template
   23032    instantiation.  Conversely, if this predicate returns false then computing
   23033    the conversion definitely won't induce template instantiation.  */
   23034 
   23035 static bool
   23036 conversion_may_instantiate_p (tree to, tree from)
   23037 {
   23038   to = non_reference (to);
   23039   from = non_reference (from);
   23040 
   23041   bool ptr_conv_p = false;
   23042   if (TYPE_PTR_P (to)
   23043       && TYPE_PTR_P (from))
   23044     {
   23045       to = TREE_TYPE (to);
   23046       from = TREE_TYPE (from);
   23047       ptr_conv_p = true;
   23048     }
   23049 
   23050   /* If one of the types is a not-yet-instantiated class template
   23051      specialization, then computing the conversion might instantiate
   23052      it in order to inspect bases, conversion functions and/or
   23053      converting constructors.  */
   23054   if ((CLASS_TYPE_P (to)
   23055        && !COMPLETE_TYPE_P (to)
   23056        && CLASSTYPE_TEMPLATE_INSTANTIATION (to))
   23057       || (CLASS_TYPE_P (from)
   23058 	  && !COMPLETE_TYPE_P (from)
   23059 	  && CLASSTYPE_TEMPLATE_INSTANTIATION (from)))
   23060     return true;
   23061 
   23062   /* Converting from one pointer type to another, or between
   23063      reference-related types, always yields a standard conversion.  */
   23064   if (ptr_conv_p || reference_related_p (to, from))
   23065     return false;
   23066 
   23067   /* Converting to a non-aggregate class type will consider its
   23068      user-declared constructors, which might induce instantiation.  */
   23069   if (CLASS_TYPE_P (to)
   23070       && CLASSTYPE_NON_AGGREGATE (to))
   23071     return true;
   23072 
   23073   /* Similarly, converting from a class type will consider its conversion
   23074      functions.  */
   23075   if (CLASS_TYPE_P (from)
   23076       && TYPE_HAS_CONVERSION (from))
   23077     return true;
   23078 
   23079   /* Otherwise, computing this conversion definitely won't induce
   23080      template instantiation.  */
   23081   return false;
   23082 }
   23083 
   23084 /* Subroutine of fn_type_unification.  PARM is a function parameter of a
   23085    template which doesn't contain any deducible template parameters; check if
   23086    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
   23087    unify_one_argument.  */
   23088 
   23089 static int
   23090 check_non_deducible_conversion (tree parm, tree arg, unification_kind_t strict,
   23091 				int flags, struct conversion **conv_p,
   23092 				bool explain_p, bool noninst_only_p)
   23093 {
   23094   tree type;
   23095 
   23096   if (!TYPE_P (arg))
   23097     type = TREE_TYPE (arg);
   23098   else
   23099     type = arg;
   23100 
   23101   if (same_type_p (parm, type))
   23102     return unify_success (explain_p);
   23103 
   23104   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
   23105   if (strict == DEDUCE_CONV)
   23106     {
   23107       if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
   23108 	return unify_success (explain_p);
   23109     }
   23110   else if (strict == DEDUCE_CALL)
   23111     {
   23112       if (conv_p && *conv_p)
   23113 	{
   23114 	  /* This conversion was already computed earlier (when
   23115 	     computing only non-instantiating conversions).  */
   23116 	  gcc_checking_assert (!noninst_only_p);
   23117 	  return unify_success (explain_p);
   23118 	}
   23119 
   23120       if (noninst_only_p
   23121 	  && conversion_may_instantiate_p (parm, type))
   23122 	return unify_success (explain_p);
   23123 
   23124       bool ok = false;
   23125       tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
   23126       if (conv_p)
   23127 	/* Avoid recalculating this in add_function_candidate.  */
   23128 	ok = (*conv_p
   23129 	      = good_conversion (parm, type, conv_arg, flags, complain));
   23130       else
   23131 	ok = can_convert_arg (parm, type, conv_arg, flags, complain);
   23132       if (ok)
   23133 	return unify_success (explain_p);
   23134     }
   23135 
   23136   if (strict == DEDUCE_EXACT)
   23137     return unify_type_mismatch (explain_p, parm, arg);
   23138   else
   23139     return unify_arg_conversion (explain_p, parm, type, arg);
   23140 }
   23141 
   23142 static bool uses_deducible_template_parms (tree type);
   23143 
   23144 /* Returns true iff the expression EXPR is one from which a template
   23145    argument can be deduced.  In other words, if it's an undecorated
   23146    use of a template non-type parameter.  */
   23147 
   23148 static bool
   23149 deducible_expression (tree expr)
   23150 {
   23151   /* Strip implicit conversions and implicit INDIRECT_REFs.  */
   23152   while (CONVERT_EXPR_P (expr)
   23153 	 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
   23154 	 || (TREE_CODE (expr) == IMPLICIT_CONV_EXPR
   23155 	     && IMPLICIT_CONV_EXPR_FORCED (expr))
   23156 	 || REFERENCE_REF_P (expr))
   23157     expr = TREE_OPERAND (expr, 0);
   23158   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
   23159 }
   23160 
   23161 /* Returns true iff the array domain DOMAIN uses a template parameter in a
   23162    deducible way; that is, if it has a max value of <PARM> - 1.  */
   23163 
   23164 static bool
   23165 deducible_array_bound (tree domain)
   23166 {
   23167   if (domain == NULL_TREE)
   23168     return false;
   23169 
   23170   tree max = TYPE_MAX_VALUE (domain);
   23171   if (TREE_CODE (max) != MINUS_EXPR)
   23172     return false;
   23173 
   23174   return deducible_expression (TREE_OPERAND (max, 0));
   23175 }
   23176 
   23177 /* Returns true iff the template arguments ARGS use a template parameter
   23178    in a deducible way.  */
   23179 
   23180 static bool
   23181 deducible_template_args (tree args)
   23182 {
   23183   for (tree elt : tree_vec_range (args))
   23184     {
   23185       bool deducible;
   23186       if (ARGUMENT_PACK_P (elt))
   23187 	deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
   23188       else
   23189 	{
   23190 	  if (PACK_EXPANSION_P (elt))
   23191 	    elt = PACK_EXPANSION_PATTERN (elt);
   23192 	  if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
   23193 	    deducible = true;
   23194 	  else if (TYPE_P (elt))
   23195 	    deducible = uses_deducible_template_parms (elt);
   23196 	  else
   23197 	    deducible = deducible_expression (elt);
   23198 	}
   23199       if (deducible)
   23200 	return true;
   23201     }
   23202   return false;
   23203 }
   23204 
   23205 /* Returns true iff TYPE contains any deducible references to template
   23206    parameters, as per 14.8.2.5.  */
   23207 
   23208 static bool
   23209 uses_deducible_template_parms (tree type)
   23210 {
   23211   if (PACK_EXPANSION_P (type))
   23212     type = PACK_EXPANSION_PATTERN (type);
   23213 
   23214   /* T
   23215      cv-list T
   23216      TT<T>
   23217      TT<i>
   23218      TT<> */
   23219   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
   23220       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
   23221     return true;
   23222 
   23223   /* T*
   23224      T&
   23225      T&&  */
   23226   if (INDIRECT_TYPE_P (type))
   23227     return uses_deducible_template_parms (TREE_TYPE (type));
   23228 
   23229   /* T[integer-constant ]
   23230      type [i]  */
   23231   if (TREE_CODE (type) == ARRAY_TYPE)
   23232     return (uses_deducible_template_parms (TREE_TYPE (type))
   23233 	    || deducible_array_bound (TYPE_DOMAIN (type)));
   23234 
   23235   /* T type ::*
   23236      type T::*
   23237      T T::*
   23238      T (type ::*)()
   23239      type (T::*)()
   23240      type (type ::*)(T)
   23241      type (T::*)(T)
   23242      T (type ::*)(T)
   23243      T (T::*)()
   23244      T (T::*)(T) */
   23245   if (TYPE_PTRMEM_P (type))
   23246     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
   23247 	    || (uses_deducible_template_parms
   23248 		(TYPE_PTRMEM_POINTED_TO_TYPE (type))));
   23249 
   23250   /* template-name <T> (where template-name refers to a class template)
   23251      template-name <i> (where template-name refers to a class template) */
   23252   if (CLASS_TYPE_P (type)
   23253       && CLASSTYPE_TEMPLATE_INFO (type)
   23254       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
   23255     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
   23256 				    (CLASSTYPE_TI_ARGS (type)));
   23257 
   23258   /* type (T)
   23259      T()
   23260      T(T)  */
   23261   if (FUNC_OR_METHOD_TYPE_P (type))
   23262     {
   23263       if (uses_deducible_template_parms (TREE_TYPE (type)))
   23264 	return true;
   23265       tree parm = TYPE_ARG_TYPES (type);
   23266       if (TREE_CODE (type) == METHOD_TYPE)
   23267 	parm = TREE_CHAIN (parm);
   23268       for (; parm; parm = TREE_CHAIN (parm))
   23269 	if (uses_deducible_template_parms (TREE_VALUE (parm)))
   23270 	  return true;
   23271       if (flag_noexcept_type
   23272 	  && TYPE_RAISES_EXCEPTIONS (type)
   23273 	  && TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))
   23274 	  && deducible_expression (TREE_PURPOSE (TYPE_RAISES_EXCEPTIONS (type))))
   23275 	return true;
   23276     }
   23277 
   23278   return false;
   23279 }
   23280 
   23281 /* Subroutine of type_unification_real and unify_pack_expansion to
   23282    handle unification of a single P/A pair.  Parameters are as
   23283    for those functions.  */
   23284 
   23285 static int
   23286 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
   23287 		    int subr, unification_kind_t strict,
   23288 		    bool explain_p)
   23289 {
   23290   tree arg_expr = NULL_TREE;
   23291   int arg_strict;
   23292 
   23293   if (arg == error_mark_node || parm == error_mark_node)
   23294     return unify_invalid (explain_p);
   23295   if (arg == unknown_type_node)
   23296     /* We can't deduce anything from this, but we might get all the
   23297        template args from other function args.  */
   23298     return unify_success (explain_p);
   23299 
   23300   /* Implicit conversions (Clause 4) will be performed on a function
   23301      argument to convert it to the type of the corresponding function
   23302      parameter if the parameter type contains no template-parameters that
   23303      participate in template argument deduction.  */
   23304   if (strict != DEDUCE_EXACT
   23305       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
   23306     /* For function parameters with no deducible template parameters,
   23307        just return.  We'll check non-dependent conversions later.  */
   23308     return unify_success (explain_p);
   23309 
   23310   switch (strict)
   23311     {
   23312     case DEDUCE_CALL:
   23313       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
   23314 		    | UNIFY_ALLOW_MORE_CV_QUAL
   23315 		    | UNIFY_ALLOW_DERIVED);
   23316       break;
   23317 
   23318     case DEDUCE_CONV:
   23319       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
   23320       break;
   23321 
   23322     case DEDUCE_EXACT:
   23323       arg_strict = UNIFY_ALLOW_NONE;
   23324       break;
   23325 
   23326     default:
   23327       gcc_unreachable ();
   23328     }
   23329 
   23330   /* We only do these transformations if this is the top-level
   23331      parameter_type_list in a call or declaration matching; in other
   23332      situations (nested function declarators, template argument lists) we
   23333      won't be comparing a type to an expression, and we don't do any type
   23334      adjustments.  */
   23335   if (!subr)
   23336     {
   23337       if (!TYPE_P (arg))
   23338 	{
   23339 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
   23340 	  if (type_unknown_p (arg))
   23341 	    {
   23342 	      /* [temp.deduct.type] A template-argument can be
   23343 		 deduced from a pointer to function or pointer
   23344 		 to member function argument if the set of
   23345 		 overloaded functions does not contain function
   23346 		 templates and at most one of a set of
   23347 		 overloaded functions provides a unique
   23348 		 match.  */
   23349 	      resolve_overloaded_unification (tparms, targs, parm,
   23350 					      arg, strict,
   23351 					      arg_strict, explain_p);
   23352 	      /* If a unique match was not found, this is a
   23353 	         non-deduced context, so we still succeed. */
   23354 	      return unify_success (explain_p);
   23355 	    }
   23356 
   23357 	  arg_expr = arg;
   23358 	  arg = unlowered_expr_type (arg);
   23359 	  if (arg == error_mark_node)
   23360 	    return unify_invalid (explain_p);
   23361 	}
   23362 
   23363       arg_strict |= maybe_adjust_types_for_deduction (tparms, strict,
   23364 						      &parm, &arg, arg_expr);
   23365     }
   23366   else
   23367     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
   23368 	!= (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
   23369       return unify_template_argument_mismatch (explain_p, parm, arg);
   23370 
   23371   /* For deduction from an init-list we need the actual list.  */
   23372   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
   23373     arg = arg_expr;
   23374   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
   23375 }
   23376 
   23377 /* for_each_template_parm callback that always returns 0.  */
   23378 
   23379 static int
   23380 zero_r (tree, void *)
   23381 {
   23382   return 0;
   23383 }
   23384 
   23385 /* for_each_template_parm any_fn callback to handle deduction of a template
   23386    type argument from the type of an array bound.  */
   23387 
   23388 static int
   23389 array_deduction_r (tree t, void *data)
   23390 {
   23391   tree_pair_p d = (tree_pair_p)data;
   23392   tree &tparms = d->purpose;
   23393   tree &targs = d->value;
   23394 
   23395   if (TREE_CODE (t) == ARRAY_TYPE)
   23396     if (tree dom = TYPE_DOMAIN (t))
   23397       if (tree max = TYPE_MAX_VALUE (dom))
   23398 	{
   23399 	  if (TREE_CODE (max) == MINUS_EXPR)
   23400 	    max = TREE_OPERAND (max, 0);
   23401 	  if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
   23402 	    unify (tparms, targs, TREE_TYPE (max), size_type_node,
   23403 		   UNIFY_ALLOW_NONE, /*explain*/false);
   23404 	}
   23405 
   23406   /* Keep walking.  */
   23407   return 0;
   23408 }
   23409 
   23410 /* Try to deduce any not-yet-deduced template type arguments from the type of
   23411    an array bound.  This is handled separately from unify because 14.8.2.5 says
   23412    "The type of a type parameter is only deduced from an array bound if it is
   23413    not otherwise deduced."  */
   23414 
   23415 static void
   23416 try_array_deduction (tree tparms, tree targs, tree parm)
   23417 {
   23418   tree_pair_s data = { tparms, targs };
   23419   hash_set<tree> visited;
   23420   for_each_template_parm (parm, zero_r, &data, &visited,
   23421 			  /*nondeduced*/false, array_deduction_r);
   23422 }
   23423 
   23424 /* Most parms like fn_type_unification.
   23425 
   23426    If SUBR is 1, we're being called recursively (to unify the
   23427    arguments of a function or method parameter of a function
   23428    template).
   23429 
   23430    CHECKS is a pointer to a vector of access checks encountered while
   23431    substituting default template arguments.  */
   23432 
   23433 static int
   23434 type_unification_real (tree tparms,
   23435 		       tree full_targs,
   23436 		       tree xparms,
   23437 		       const tree *xargs,
   23438 		       unsigned int xnargs,
   23439 		       int subr,
   23440 		       unification_kind_t strict,
   23441 		       vec<deferred_access_check, va_gc> **checks,
   23442 		       bool explain_p)
   23443 {
   23444   tree parm, arg;
   23445   int i;
   23446   int ntparms = TREE_VEC_LENGTH (tparms);
   23447   int saw_undeduced = 0;
   23448   tree parms;
   23449   const tree *args;
   23450   unsigned int nargs;
   23451   unsigned int ia;
   23452 
   23453   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
   23454   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
   23455   gcc_assert (ntparms > 0);
   23456 
   23457   tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
   23458 
   23459   /* Reset the number of non-defaulted template arguments contained
   23460      in TARGS.  */
   23461   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
   23462 
   23463  again:
   23464   parms = xparms;
   23465   args = xargs;
   23466   nargs = xnargs;
   23467 
   23468   /* Only fn_type_unification cares about terminal void.  */
   23469   if (nargs && args[nargs-1] == void_type_node)
   23470     --nargs;
   23471 
   23472   ia = 0;
   23473   while (parms && parms != void_list_node
   23474 	 && ia < nargs)
   23475     {
   23476       parm = TREE_VALUE (parms);
   23477 
   23478       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
   23479 	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
   23480 	/* For a function parameter pack that occurs at the end of the
   23481 	   parameter-declaration-list, the type A of each remaining
   23482 	   argument of the call is compared with the type P of the
   23483 	   declarator-id of the function parameter pack.  */
   23484 	break;
   23485 
   23486       parms = TREE_CHAIN (parms);
   23487 
   23488       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
   23489 	/* For a function parameter pack that does not occur at the
   23490 	   end of the parameter-declaration-list, the type of the
   23491 	   parameter pack is a non-deduced context.  */
   23492 	continue;
   23493 
   23494       /* [temp.deduct.conv] only applies to the deduction of the return
   23495 	 type, which is always the first argument here.  Other arguments
   23496 	 (notably, explicit object parameters) should undergo normal
   23497 	 call-like unification.  */
   23498       unification_kind_t kind = strict;
   23499       if (strict == DEDUCE_CONV && ia > 0)
   23500 	kind = DEDUCE_CALL;
   23501 
   23502       arg = args[ia];
   23503       ++ia;
   23504 
   23505       if (unify_one_argument (tparms, full_targs, parm, arg, subr, kind,
   23506 			      explain_p))
   23507 	return 1;
   23508     }
   23509 
   23510   if (parms
   23511       && parms != void_list_node
   23512       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
   23513     {
   23514       gcc_assert (strict != DEDUCE_CONV);
   23515 
   23516       /* Unify the remaining arguments with the pack expansion type.  */
   23517       tree argvec;
   23518       tree parmvec = make_tree_vec (1);
   23519 
   23520       /* Allocate a TREE_VEC and copy in all of the arguments */
   23521       argvec = make_tree_vec (nargs - ia);
   23522       for (i = 0; ia < nargs; ++ia, ++i)
   23523 	TREE_VEC_ELT (argvec, i) = args[ia];
   23524 
   23525       /* Copy the parameter into parmvec.  */
   23526       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
   23527       if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
   23528                                 /*subr=*/subr, explain_p))
   23529         return 1;
   23530 
   23531       /* Advance to the end of the list of parameters.  */
   23532       parms = TREE_CHAIN (parms);
   23533     }
   23534 
   23535   /* Fail if we've reached the end of the parm list, and more args
   23536      are present, and the parm list isn't variadic.  */
   23537   if (ia < nargs && parms == void_list_node)
   23538     return unify_too_many_arguments (explain_p, nargs, ia);
   23539   /* Fail if parms are left and they don't have default values and
   23540      they aren't all deduced as empty packs (c++/57397).  This is
   23541      consistent with sufficient_parms_p.  */
   23542   if (parms && parms != void_list_node
   23543       && TREE_PURPOSE (parms) == NULL_TREE)
   23544     {
   23545       unsigned int count = nargs;
   23546       tree p = parms;
   23547       bool type_pack_p;
   23548       do
   23549 	{
   23550 	  type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
   23551 	  if (!type_pack_p)
   23552 	    count++;
   23553 	  p = TREE_CHAIN (p);
   23554 	}
   23555       while (p && p != void_list_node);
   23556       if (count != nargs)
   23557 	return unify_too_few_arguments (explain_p, ia, count,
   23558 					type_pack_p);
   23559     }
   23560 
   23561   if (!subr)
   23562     {
   23563       tsubst_flags_t complain = (explain_p
   23564 				 ? tf_warning_or_error
   23565 				 : tf_none);
   23566       bool tried_array_deduction = (cxx_dialect < cxx17);
   23567 
   23568       for (i = 0; i < ntparms; i++)
   23569 	{
   23570 	  tree targ = TREE_VEC_ELT (targs, i);
   23571 	  tree tparm = TREE_VEC_ELT (tparms, i);
   23572 
   23573 	  /* Clear the "incomplete" flags on all argument packs now so that
   23574 	     substituting them into later default arguments works.  */
   23575 	  if (targ && ARGUMENT_PACK_P (targ))
   23576             {
   23577               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
   23578               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
   23579             }
   23580 
   23581 	  if (targ || tparm == error_mark_node)
   23582 	    continue;
   23583 	  tparm = TREE_VALUE (tparm);
   23584 
   23585 	  if (TREE_CODE (tparm) == TYPE_DECL
   23586 	      && !tried_array_deduction)
   23587 	    {
   23588 	      try_array_deduction (tparms, targs, xparms);
   23589 	      tried_array_deduction = true;
   23590 	      if (TREE_VEC_ELT (targs, i))
   23591 		continue;
   23592 	    }
   23593 
   23594 	  /* If this is an undeduced nontype parameter that depends on
   23595 	     a type parameter, try another pass; its type may have been
   23596 	     deduced from a later argument than the one from which
   23597 	     this parameter can be deduced.  */
   23598 	  if (TREE_CODE (tparm) == PARM_DECL
   23599 	      && !is_auto (TREE_TYPE (tparm))
   23600 	      && uses_template_parms (TREE_TYPE (tparm))
   23601 	      && saw_undeduced < 2)
   23602 	    {
   23603 	      saw_undeduced = 1;
   23604 	      continue;
   23605 	    }
   23606 
   23607 	  /* Core issue #226 (C++0x) [temp.deduct]:
   23608 
   23609 	     If a template argument has not been deduced, its
   23610 	     default template argument, if any, is used.
   23611 
   23612 	     When we are in C++98 mode, TREE_PURPOSE will either
   23613 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
   23614 	     to explicitly check cxx_dialect here.  */
   23615 	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
   23616 	    /* OK, there is a default argument.  Wait until after the
   23617 	       conversion check to do substitution.  */
   23618 	    continue;
   23619 
   23620 	  /* If the type parameter is a parameter pack, then it will
   23621 	     be deduced to an empty parameter pack.  */
   23622 	  if (template_parameter_pack_p (tparm))
   23623 	    {
   23624 	      tree arg;
   23625 
   23626 	      if (TREE_CODE (tparm) == PARM_DECL)
   23627 		{
   23628 		  arg = make_node (NONTYPE_ARGUMENT_PACK);
   23629 		  TREE_CONSTANT (arg) = 1;
   23630 		}
   23631 	      else
   23632 		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
   23633 
   23634 	      ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
   23635 
   23636 	      TREE_VEC_ELT (targs, i) = arg;
   23637 	      continue;
   23638 	    }
   23639 
   23640 	  return unify_parameter_deduction_failure (explain_p, tparm);
   23641 	}
   23642 
   23643       /* During partial ordering, we deduce dependent template args.  */
   23644       bool any_dependent_targs = false;
   23645 
   23646       /* Now substitute into the default template arguments.  */
   23647       for (i = 0; i < ntparms; i++)
   23648 	{
   23649 	  tree targ = TREE_VEC_ELT (targs, i);
   23650 	  tree tparm = TREE_VEC_ELT (tparms, i);
   23651 
   23652 	  if (targ)
   23653 	    {
   23654 	      if (!any_dependent_targs && dependent_template_arg_p (targ))
   23655 		any_dependent_targs = true;
   23656 	      continue;
   23657 	    }
   23658 	  if (tparm == error_mark_node)
   23659 	    continue;
   23660 
   23661 	  tree parm = TREE_VALUE (tparm);
   23662 	  tree arg = TREE_PURPOSE (tparm);
   23663 	  reopen_deferring_access_checks (*checks);
   23664 	  location_t save_loc = input_location;
   23665 	  if (DECL_P (parm))
   23666 	    input_location = DECL_SOURCE_LOCATION (parm);
   23667 
   23668 	  if (saw_undeduced == 1
   23669 	      && TREE_CODE (parm) == PARM_DECL
   23670 	      && !is_auto (TREE_TYPE (parm))
   23671 	      && uses_template_parms (TREE_TYPE (parm)))
   23672 	    {
   23673 	      /* The type of this non-type parameter depends on undeduced
   23674 		 parameters.  Don't try to use its default argument yet,
   23675 		 since we might deduce an argument for it on the next pass,
   23676 		 but do check whether the arguments we already have cause
   23677 		 substitution failure, so that that happens before we try
   23678 		 later default arguments (78489).  */
   23679 	      ++processing_template_decl;
   23680 	      tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
   23681 				  NULL_TREE);
   23682 	      --processing_template_decl;
   23683 	      if (type == error_mark_node)
   23684 		arg = error_mark_node;
   23685 	      else
   23686 		arg = NULL_TREE;
   23687 	    }
   23688 	  else
   23689 	    {
   23690 	      /* Even if the call is happening in template context, getting
   23691 		 here means it's non-dependent, and a default argument is
   23692 		 considered a separate definition under [temp.decls], so we can
   23693 		 do this substitution without processing_template_decl.  This
   23694 		 is important if the default argument contains something that
   23695 		 might be instantiation-dependent like access (87480).  */
   23696 	      processing_template_decl_sentinel s (!any_dependent_targs);
   23697 	      tree substed = NULL_TREE;
   23698 	      if (saw_undeduced == 1 && !any_dependent_targs)
   23699 		{
   23700 		  /* First instatiate in template context, in case we still
   23701 		     depend on undeduced template parameters.  */
   23702 		  ++processing_template_decl;
   23703 		  substed = tsubst_template_arg (arg, full_targs, complain,
   23704 						 NULL_TREE);
   23705 		  --processing_template_decl;
   23706 		  if (substed != error_mark_node
   23707 		      && !uses_template_parms (substed))
   23708 		    /* We replaced all the tparms, substitute again out of
   23709 		       template context.  */
   23710 		    substed = NULL_TREE;
   23711 		  else
   23712 		    processing_template_decl = 1;
   23713 		}
   23714 	      if (!substed)
   23715 		substed = tsubst_template_arg (arg, full_targs, complain,
   23716 					       NULL_TREE);
   23717 
   23718 	      if (!processing_template_decl || !uses_template_parms (substed))
   23719 		arg = convert_template_argument (parm, substed, full_targs,
   23720 						 complain, i, NULL_TREE);
   23721 	      else if (saw_undeduced == 1)
   23722 		arg = NULL_TREE;
   23723 	      else if (!any_dependent_targs)
   23724 		arg = error_mark_node;
   23725 	    }
   23726 
   23727 	  input_location = save_loc;
   23728 	  *checks = get_deferred_access_checks ();
   23729 	  pop_deferring_access_checks ();
   23730 
   23731 	  if (arg == error_mark_node)
   23732 	    return 1;
   23733 	  else if (arg)
   23734 	    {
   23735 	      TREE_VEC_ELT (targs, i) = arg;
   23736 	      /* The position of the first default template argument,
   23737 		 is also the number of non-defaulted arguments in TARGS.
   23738 		 Record that.  */
   23739 	      if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
   23740 		SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
   23741 	    }
   23742 	}
   23743 
   23744       if (saw_undeduced++ == 1)
   23745 	goto again;
   23746     }
   23747 
   23748   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
   23749     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
   23750 
   23751   return unify_success (explain_p);
   23752 }
   23753 
   23754 /* Subroutine of type_unification_real.  Args are like the variables
   23755    at the call site.  ARG is an overloaded function (or template-id);
   23756    we try deducing template args from each of the overloads, and if
   23757    only one succeeds, we go with that.  Modifies TARGS and returns
   23758    true on success.  */
   23759 
   23760 static bool
   23761 resolve_overloaded_unification (tree tparms,
   23762 				tree targs,
   23763 				tree parm,
   23764 				tree arg,
   23765 				unification_kind_t strict,
   23766 				int sub_strict,
   23767 			        bool explain_p)
   23768 {
   23769   tree tempargs = copy_node (targs);
   23770   int good = 0;
   23771   tree goodfn = NULL_TREE;
   23772   bool addr_p;
   23773 
   23774   if (TREE_CODE (arg) == ADDR_EXPR)
   23775     {
   23776       arg = TREE_OPERAND (arg, 0);
   23777       addr_p = true;
   23778     }
   23779   else
   23780     addr_p = false;
   23781 
   23782   if (TREE_CODE (arg) == COMPONENT_REF)
   23783     /* Handle `&x' where `x' is some static or non-static member
   23784        function name.  */
   23785     arg = TREE_OPERAND (arg, 1);
   23786 
   23787   if (TREE_CODE (arg) == OFFSET_REF)
   23788     arg = TREE_OPERAND (arg, 1);
   23789 
   23790   /* Strip baselink information.  */
   23791   if (BASELINK_P (arg))
   23792     arg = BASELINK_FUNCTIONS (arg);
   23793 
   23794   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
   23795     {
   23796       /* If we got some explicit template args, we need to plug them into
   23797 	 the affected templates before we try to unify, in case the
   23798 	 explicit args will completely resolve the templates in question.  */
   23799 
   23800       int ok = 0;
   23801       tree expl_subargs = TREE_OPERAND (arg, 1);
   23802       arg = TREE_OPERAND (arg, 0);
   23803 
   23804       for (lkp_iterator iter (arg); iter; ++iter)
   23805 	{
   23806 	  tree fn = *iter;
   23807 	  tree subargs, elem;
   23808 
   23809 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
   23810 	    continue;
   23811 
   23812 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
   23813 					   expl_subargs, NULL_TREE, tf_none);
   23814 	  if (subargs != error_mark_node
   23815 	      && !any_dependent_template_arguments_p (subargs))
   23816 	    {
   23817 	      fn = instantiate_template (fn, subargs, tf_none);
   23818 	      if (!constraints_satisfied_p (fn))
   23819 		continue;
   23820 	      if (undeduced_auto_decl (fn))
   23821 		{
   23822 		  /* Instantiate the function to deduce its return type.  */
   23823 		  ++function_depth;
   23824 		  instantiate_decl (fn, /*defer*/false, /*class*/false);
   23825 		  --function_depth;
   23826 		}
   23827 
   23828 	      if (flag_noexcept_type)
   23829 		maybe_instantiate_noexcept (fn, tf_none);
   23830 
   23831 	      elem = TREE_TYPE (fn);
   23832 	      if (try_one_overload (tparms, targs, tempargs, parm,
   23833 				    elem, strict, sub_strict, addr_p, explain_p)
   23834 		  && (!goodfn || !same_type_p (goodfn, elem)))
   23835 		{
   23836 		  goodfn = elem;
   23837 		  ++good;
   23838 		}
   23839 	    }
   23840 	  else if (subargs)
   23841 	    ++ok;
   23842 	}
   23843       /* If no templates (or more than one) are fully resolved by the
   23844 	 explicit arguments, this template-id is a non-deduced context; it
   23845 	 could still be OK if we deduce all template arguments for the
   23846 	 enclosing call through other arguments.  */
   23847       if (good != 1)
   23848 	good = ok;
   23849     }
   23850   else if (!OVL_P (arg))
   23851     /* If ARG is, for example, "(0, &f)" then its type will be unknown
   23852        -- but the deduction does not succeed because the expression is
   23853        not just the function on its own.  */
   23854     return false;
   23855   else
   23856     for (lkp_iterator iter (arg); iter; ++iter)
   23857       {
   23858 	tree fn = *iter;
   23859 	if (flag_noexcept_type)
   23860 	  maybe_instantiate_noexcept (fn, tf_none);
   23861 	if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
   23862 			      strict, sub_strict, addr_p, explain_p)
   23863 	    && (!goodfn || !decls_match (goodfn, fn)))
   23864 	  {
   23865 	    goodfn = fn;
   23866 	    ++good;
   23867 	  }
   23868       }
   23869 
   23870   /* [temp.deduct.type] A template-argument can be deduced from a pointer
   23871      to function or pointer to member function argument if the set of
   23872      overloaded functions does not contain function templates and at most
   23873      one of a set of overloaded functions provides a unique match.
   23874 
   23875      So if we found multiple possibilities, we return success but don't
   23876      deduce anything.  */
   23877 
   23878   if (good == 1)
   23879     {
   23880       int i = TREE_VEC_LENGTH (targs);
   23881       for (; i--; )
   23882 	if (TREE_VEC_ELT (tempargs, i))
   23883 	  {
   23884 	    tree old = TREE_VEC_ELT (targs, i);
   23885 	    tree new_ = TREE_VEC_ELT (tempargs, i);
   23886 	    if (new_ && old && ARGUMENT_PACK_P (old)
   23887 		&& ARGUMENT_PACK_EXPLICIT_ARGS (old))
   23888 	      /* Don't forget explicit template arguments in a pack.  */
   23889 	      ARGUMENT_PACK_EXPLICIT_ARGS (new_)
   23890 		= ARGUMENT_PACK_EXPLICIT_ARGS (old);
   23891 	    TREE_VEC_ELT (targs, i) = new_;
   23892 	  }
   23893     }
   23894   if (good)
   23895     return true;
   23896 
   23897   return false;
   23898 }
   23899 
   23900 /* Core DR 115: In contexts where deduction is done and fails, or in
   23901    contexts where deduction is not done, if a template argument list is
   23902    specified and it, along with any default template arguments, identifies
   23903    a single function template specialization, then the template-id is an
   23904    lvalue for the function template specialization.  */
   23905 
   23906 tree
   23907 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
   23908 {
   23909   tree expr, offset, baselink;
   23910   bool addr;
   23911 
   23912   if (!type_unknown_p (orig_expr))
   23913     return orig_expr;
   23914 
   23915   expr = orig_expr;
   23916   addr = false;
   23917   offset = NULL_TREE;
   23918   baselink = NULL_TREE;
   23919 
   23920   if (TREE_CODE (expr) == ADDR_EXPR)
   23921     {
   23922       expr = TREE_OPERAND (expr, 0);
   23923       addr = true;
   23924     }
   23925   if (TREE_CODE (expr) == OFFSET_REF)
   23926     {
   23927       offset = expr;
   23928       expr = TREE_OPERAND (expr, 1);
   23929     }
   23930   if (BASELINK_P (expr))
   23931     {
   23932       baselink = expr;
   23933       expr = BASELINK_FUNCTIONS (expr);
   23934     }
   23935 
   23936   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
   23937     {
   23938       int good = 0;
   23939       tree goodfn = NULL_TREE;
   23940 
   23941       /* If we got some explicit template args, we need to plug them into
   23942 	 the affected templates before we try to unify, in case the
   23943 	 explicit args will completely resolve the templates in question.  */
   23944 
   23945       tree expl_subargs = TREE_OPERAND (expr, 1);
   23946       tree arg = TREE_OPERAND (expr, 0);
   23947       tree badfn = NULL_TREE;
   23948       tree badargs = NULL_TREE;
   23949 
   23950       for (lkp_iterator iter (arg); iter; ++iter)
   23951 	{
   23952 	  tree fn = *iter;
   23953 	  tree subargs, elem;
   23954 
   23955 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
   23956 	    continue;
   23957 
   23958 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
   23959 					   expl_subargs, NULL_TREE, tf_none);
   23960 	  if (subargs != error_mark_node
   23961 	      && !any_dependent_template_arguments_p (subargs))
   23962 	    {
   23963 	      elem = instantiate_template (fn, subargs, tf_none);
   23964 	      if (elem == error_mark_node)
   23965 		{
   23966 		  badfn = fn;
   23967 		  badargs = subargs;
   23968 		}
   23969 	      else if (elem && (!goodfn || !decls_match (goodfn, elem))
   23970 		       && constraints_satisfied_p (elem))
   23971 		{
   23972 		  goodfn = elem;
   23973 		  ++good;
   23974 		}
   23975 	    }
   23976 	}
   23977       if (good == 1)
   23978 	{
   23979 	  mark_used (goodfn);
   23980 	  expr = goodfn;
   23981 	  if (baselink)
   23982 	    expr = build_baselink (BASELINK_BINFO (baselink),
   23983 				   BASELINK_ACCESS_BINFO (baselink),
   23984 				   expr, BASELINK_OPTYPE (baselink));
   23985 	  if (offset)
   23986 	    {
   23987 	      tree base
   23988 		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
   23989 	      expr = build_offset_ref (base, expr, addr, complain);
   23990 	    }
   23991 	  if (addr)
   23992 	    expr = cp_build_addr_expr (expr, complain);
   23993 	  return expr;
   23994 	}
   23995       else if (good == 0 && badargs && (complain & tf_error))
   23996 	/* There were no good options and at least one bad one, so let the
   23997 	   user know what the problem is.  */
   23998 	instantiate_template (badfn, badargs, complain);
   23999     }
   24000   return orig_expr;
   24001 }
   24002 
   24003 /* As above, but error out if the expression remains overloaded.  */
   24004 
   24005 tree
   24006 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
   24007 {
   24008   exp = resolve_nondeduced_context (exp, complain);
   24009   if (type_unknown_p (exp))
   24010     {
   24011       if (complain & tf_error)
   24012 	cxx_incomplete_type_error (exp, TREE_TYPE (exp));
   24013       return error_mark_node;
   24014     }
   24015   return exp;
   24016 }
   24017 
   24018 /* Subroutine of resolve_overloaded_unification; does deduction for a single
   24019    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
   24020    different overloads deduce different arguments for a given parm.
   24021    ADDR_P is true if the expression for which deduction is being
   24022    performed was of the form "& fn" rather than simply "fn".
   24023 
   24024    Returns 1 on success.  */
   24025 
   24026 static int
   24027 try_one_overload (tree tparms,
   24028 		  tree orig_targs,
   24029 		  tree targs,
   24030 		  tree parm,
   24031 		  tree arg,
   24032 		  unification_kind_t strict,
   24033 		  int sub_strict,
   24034 		  bool addr_p,
   24035 		  bool explain_p)
   24036 {
   24037   int nargs;
   24038   tree tempargs;
   24039   int i;
   24040 
   24041   if (arg == error_mark_node)
   24042     return 0;
   24043 
   24044   /* [temp.deduct.type] A template-argument can be deduced from a pointer
   24045      to function or pointer to member function argument if the set of
   24046      overloaded functions does not contain function templates and at most
   24047      one of a set of overloaded functions provides a unique match.
   24048 
   24049      So if this is a template, just return success.  */
   24050 
   24051   if (uses_template_parms (arg))
   24052     return 1;
   24053 
   24054   if (TREE_CODE (arg) == METHOD_TYPE)
   24055     arg = build_ptrmemfunc_type (build_pointer_type (arg));
   24056   else if (addr_p)
   24057     arg = build_pointer_type (arg);
   24058 
   24059   sub_strict |= maybe_adjust_types_for_deduction (tparms, strict,
   24060 						  &parm, &arg, NULL_TREE);
   24061 
   24062   /* We don't copy orig_targs for this because if we have already deduced
   24063      some template args from previous args, unify would complain when we
   24064      try to deduce a template parameter for the same argument, even though
   24065      there isn't really a conflict.  */
   24066   nargs = TREE_VEC_LENGTH (targs);
   24067   tempargs = make_tree_vec (nargs);
   24068 
   24069   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
   24070     return 0;
   24071 
   24072   /* First make sure we didn't deduce anything that conflicts with
   24073      explicitly specified args.  */
   24074   for (i = nargs; i--; )
   24075     {
   24076       tree elt = TREE_VEC_ELT (tempargs, i);
   24077       tree oldelt = TREE_VEC_ELT (orig_targs, i);
   24078 
   24079       if (!elt)
   24080 	/*NOP*/;
   24081       else if (uses_template_parms (elt))
   24082 	/* Since we're unifying against ourselves, we will fill in
   24083 	   template args used in the function parm list with our own
   24084 	   template parms.  Discard them.  */
   24085 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
   24086       else if (oldelt && ARGUMENT_PACK_P (oldelt))
   24087 	{
   24088 	  /* Check that the argument at each index of the deduced argument pack
   24089 	     is equivalent to the corresponding explicitly specified argument.
   24090 	     We may have deduced more arguments than were explicitly specified,
   24091 	     and that's OK.  */
   24092 
   24093 	  /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
   24094 	     that's wrong if we deduce the same argument pack from multiple
   24095 	     function arguments: it's only incomplete the first time.  */
   24096 
   24097 	  tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
   24098 	  tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
   24099 
   24100 	  if (TREE_VEC_LENGTH (deduced_pack)
   24101 	      < TREE_VEC_LENGTH (explicit_pack))
   24102 	    return 0;
   24103 
   24104 	  for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
   24105 	    if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
   24106 				      TREE_VEC_ELT (deduced_pack, j)))
   24107 	      return 0;
   24108 	}
   24109       else if (oldelt && !template_args_equal (oldelt, elt))
   24110 	return 0;
   24111     }
   24112 
   24113   for (i = nargs; i--; )
   24114     {
   24115       tree elt = TREE_VEC_ELT (tempargs, i);
   24116 
   24117       if (elt)
   24118 	TREE_VEC_ELT (targs, i) = elt;
   24119     }
   24120 
   24121   return 1;
   24122 }
   24123 
   24124 /* PARM is a template class (perhaps with unbound template
   24125    parameters).  ARG is a fully instantiated type.  If ARG can be
   24126    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
   24127    TARGS are as for unify.  */
   24128 
   24129 static tree
   24130 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
   24131 		       bool explain_p)
   24132 {
   24133   if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
   24134     return NULL_TREE;
   24135   else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
   24136     /* Matches anything.  */;
   24137   else if (CLASSTYPE_TI_TEMPLATE (arg) != CLASSTYPE_TI_TEMPLATE (parm))
   24138     return NULL_TREE;
   24139 
   24140   /* We need to make a new template argument vector for the call to
   24141      unify.  If we used TARGS, we'd clutter it up with the result of
   24142      the attempted unification, even if this class didn't work out.
   24143      We also don't want to commit ourselves to all the unifications
   24144      we've already done, since unification is supposed to be done on
   24145      an argument-by-argument basis.  In other words, consider the
   24146      following pathological case:
   24147 
   24148        template <int I, int J, int K>
   24149        struct S {};
   24150 
   24151        template <int I, int J>
   24152        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
   24153 
   24154        template <int I, int J, int K>
   24155        void f(S<I, J, K>, S<I, I, I>);
   24156 
   24157        void g() {
   24158 	 S<0, 0, 0> s0;
   24159 	 S<0, 1, 2> s2;
   24160 
   24161 	 f(s0, s2);
   24162        }
   24163 
   24164      Now, by the time we consider the unification involving `s2', we
   24165      already know that we must have `f<0, 0, 0>'.  But, even though
   24166      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
   24167      because there are two ways to unify base classes of S<0, 1, 2>
   24168      with S<I, I, I>.  If we kept the already deduced knowledge, we
   24169      would reject the possibility I=1.  */
   24170   targs = copy_template_args (targs);
   24171   for (tree& targ : tree_vec_range (INNERMOST_TEMPLATE_ARGS (targs)))
   24172     targ = NULL_TREE;
   24173 
   24174   int err;
   24175   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
   24176     err = unify_bound_ttp_args (tparms, targs, parm, arg, explain_p);
   24177   else
   24178     err = unify (tparms, targs,
   24179 		 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (parm)),
   24180 		 INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (arg)),
   24181 		 UNIFY_ALLOW_NONE, explain_p);
   24182 
   24183   return err ? NULL_TREE : arg;
   24184 }
   24185 
   24186 /* Given a template type PARM and a class type ARG, find the unique
   24187    base type in ARG that is an instance of PARM.  We do not examine
   24188    ARG itself; only its base-classes.  If there is not exactly one
   24189    appropriate base class, return NULL_TREE.  PARM may be the type of
   24190    a partial specialization, as well as a plain template type.  Used
   24191    by unify.  */
   24192 
   24193 static enum template_base_result
   24194 get_template_base (tree tparms, tree targs, tree parm, tree arg,
   24195 		   bool explain_p, tree *result)
   24196 {
   24197   tree rval = NULL_TREE;
   24198   tree binfo;
   24199 
   24200   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
   24201 
   24202   binfo = TYPE_BINFO (complete_type (arg));
   24203   if (!binfo)
   24204     {
   24205       /* The type could not be completed.  */
   24206       *result = NULL_TREE;
   24207       return tbr_incomplete_type;
   24208     }
   24209 
   24210   /* Walk in inheritance graph order.  The search order is not
   24211      important, and this avoids multiple walks of virtual bases.  */
   24212   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
   24213     {
   24214       tree r = try_class_unification (tparms, targs, parm,
   24215 				      BINFO_TYPE (binfo), explain_p);
   24216 
   24217       if (r)
   24218 	{
   24219 	  /* If there is more than one satisfactory baseclass, then:
   24220 
   24221 	       [temp.deduct.call]
   24222 
   24223 	      If they yield more than one possible deduced A, the type
   24224 	      deduction fails.
   24225 
   24226 	     applies.  */
   24227 	  if (rval && !same_type_p (r, rval))
   24228 	    {
   24229 	      /* [temp.deduct.call]/4.3: If there is a class C that is a
   24230 		 (direct or indirect) base class of D and derived (directly or
   24231 		 indirectly) from a class B and that would be a valid deduced
   24232 		 A, the deduced A cannot be B or pointer to B, respectively. */
   24233 	      if (DERIVED_FROM_P (r, rval))
   24234 		/* Ignore r.  */
   24235 		continue;
   24236 	      else if (DERIVED_FROM_P (rval, r))
   24237 		/* Ignore rval.  */;
   24238 	      else
   24239 		{
   24240 		  *result = NULL_TREE;
   24241 		  return tbr_ambiguous_baseclass;
   24242 		}
   24243 	    }
   24244 
   24245 	  rval = r;
   24246 	}
   24247     }
   24248 
   24249   *result = rval;
   24250   return tbr_success;
   24251 }
   24252 
   24253 /* Returns the level of DECL, which declares a template parameter.  */
   24254 
   24255 static int
   24256 template_decl_level (tree decl)
   24257 {
   24258   switch (TREE_CODE (decl))
   24259     {
   24260     case TYPE_DECL:
   24261     case TEMPLATE_DECL:
   24262       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
   24263 
   24264     case PARM_DECL:
   24265       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
   24266 
   24267     default:
   24268       gcc_unreachable ();
   24269     }
   24270   return 0;
   24271 }
   24272 
   24273 /* Decide whether ARG can be unified with PARM, considering only the
   24274    cv-qualifiers of each type, given STRICT as documented for unify.
   24275    Returns nonzero iff the unification is OK on that basis.  */
   24276 
   24277 static int
   24278 check_cv_quals_for_unify (int strict, tree arg, tree parm)
   24279 {
   24280   int arg_quals = cp_type_quals (arg);
   24281   int parm_quals = cp_type_quals (parm);
   24282 
   24283   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
   24284       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
   24285     {
   24286       /*  Although a CVR qualifier is ignored when being applied to a
   24287 	  substituted template parameter ([8.3.2]/1 for example), that
   24288 	  does not allow us to unify "const T" with "int&" because both
   24289 	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
   24290 	  It is ok when we're allowing additional CV qualifiers
   24291 	  at the outer level [14.8.2.1]/3,1st bullet.  */
   24292       if ((TYPE_REF_P (arg)
   24293 	   || FUNC_OR_METHOD_TYPE_P (arg))
   24294 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
   24295 	return 0;
   24296 
   24297       if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
   24298 	  && (parm_quals & TYPE_QUAL_RESTRICT))
   24299 	return 0;
   24300     }
   24301 
   24302   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
   24303       && (arg_quals & parm_quals) != parm_quals)
   24304     return 0;
   24305 
   24306   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
   24307       && (parm_quals & arg_quals) != arg_quals)
   24308     return 0;
   24309 
   24310   return 1;
   24311 }
   24312 
   24313 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
   24314 void
   24315 template_parm_level_and_index (tree parm, int* level, int* index)
   24316 {
   24317   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
   24318       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
   24319       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
   24320     {
   24321       *index = TEMPLATE_TYPE_IDX (parm);
   24322       *level = TEMPLATE_TYPE_LEVEL (parm);
   24323     }
   24324   else
   24325     {
   24326       *index = TEMPLATE_PARM_IDX (parm);
   24327       *level = TEMPLATE_PARM_LEVEL (parm);
   24328     }
   24329 }
   24330 
   24331 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
   24332   do {									\
   24333     if (unify (TP, TA, P, A, S, EP))					\
   24334       return 1;								\
   24335   } while (0)
   24336 
   24337 /* Unifies the remaining arguments in PACKED_ARGS with the pack
   24338    expansion at the end of PACKED_PARMS. Returns 0 if the type
   24339    deduction succeeds, 1 otherwise. STRICT is the same as in
   24340    fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
   24341    function call argument list. We'll need to adjust the arguments to make them
   24342    types. SUBR tells us if this is from a recursive call to
   24343    type_unification_real, or for comparing two template argument
   24344    lists. */
   24345 
   24346 static int
   24347 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
   24348                       tree packed_args, unification_kind_t strict,
   24349                       bool subr, bool explain_p)
   24350 {
   24351   tree parm
   24352     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
   24353   tree pattern = PACK_EXPANSION_PATTERN (parm);
   24354   tree pack, packs = NULL_TREE;
   24355   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
   24356 
   24357   /* Add in any args remembered from an earlier partial instantiation.  */
   24358   targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
   24359   int levels = TMPL_ARGS_DEPTH (targs);
   24360 
   24361   packed_args = expand_template_argument_pack (packed_args);
   24362 
   24363   int len = TREE_VEC_LENGTH (packed_args);
   24364 
   24365   /* Determine the parameter packs we will be deducing from the
   24366      pattern, and record their current deductions.  */
   24367   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
   24368        pack; pack = TREE_CHAIN (pack))
   24369     {
   24370       tree parm_pack = TREE_VALUE (pack);
   24371       int idx, level;
   24372 
   24373       /* Only template parameter packs can be deduced, not e.g. function
   24374 	 parameter packs or __bases or __integer_pack.  */
   24375       if (!TEMPLATE_PARM_P (parm_pack))
   24376 	continue;
   24377 
   24378       /* Determine the index and level of this parameter pack.  */
   24379       template_parm_level_and_index (parm_pack, &level, &idx);
   24380       if (level > levels)
   24381 	continue;
   24382 
   24383       /* Keep track of the parameter packs and their corresponding
   24384          argument packs.  */
   24385       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
   24386       TREE_TYPE (packs) = make_tree_vec (len - start);
   24387     }
   24388 
   24389   /* Loop through all of the arguments that have not yet been
   24390      unified and unify each with the pattern.  */
   24391   for (i = start; i < len; i++)
   24392     {
   24393       tree parm;
   24394       bool any_explicit = false;
   24395       tree arg = TREE_VEC_ELT (packed_args, i);
   24396 
   24397       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
   24398 	 or the element of its argument pack at the current index if
   24399 	 this argument was explicitly specified.  */
   24400       for (pack = packs; pack; pack = TREE_CHAIN (pack))
   24401         {
   24402           int idx, level;
   24403           tree arg, pargs;
   24404           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
   24405 
   24406           arg = NULL_TREE;
   24407           if (TREE_VALUE (pack)
   24408               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
   24409               && (i - start < TREE_VEC_LENGTH (pargs)))
   24410             {
   24411               any_explicit = true;
   24412               arg = TREE_VEC_ELT (pargs, i - start);
   24413             }
   24414           TMPL_ARG (targs, level, idx) = arg;
   24415         }
   24416 
   24417       /* If we had explicit template arguments, substitute them into the
   24418 	 pattern before deduction.  */
   24419       if (any_explicit)
   24420 	{
   24421 	  /* Some arguments might still be unspecified or dependent.  */
   24422 	  bool dependent;
   24423 	  ++processing_template_decl;
   24424 	  dependent = any_dependent_template_arguments_p (targs);
   24425 	  if (!dependent)
   24426 	    --processing_template_decl;
   24427 	  parm = tsubst (pattern, targs,
   24428 			 explain_p ? tf_warning_or_error : tf_none,
   24429 			 NULL_TREE);
   24430 	  if (dependent)
   24431 	    --processing_template_decl;
   24432 	  if (parm == error_mark_node)
   24433 	    return 1;
   24434 	}
   24435       else
   24436 	parm = pattern;
   24437 
   24438       /* Unify the pattern with the current argument.  */
   24439       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
   24440 			      explain_p))
   24441 	return 1;
   24442 
   24443       /* For each parameter pack, collect the deduced value.  */
   24444       for (pack = packs; pack; pack = TREE_CHAIN (pack))
   24445         {
   24446           int idx, level;
   24447           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
   24448 
   24449           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
   24450             TMPL_ARG (targs, level, idx);
   24451         }
   24452     }
   24453 
   24454   /* Verify that the results of unification with the parameter packs
   24455      produce results consistent with what we've seen before, and make
   24456      the deduced argument packs available.  */
   24457   for (pack = packs; pack; pack = TREE_CHAIN (pack))
   24458     {
   24459       tree old_pack = TREE_VALUE (pack);
   24460       tree new_args = TREE_TYPE (pack);
   24461       int i, len = TREE_VEC_LENGTH (new_args);
   24462       int idx, level;
   24463       bool nondeduced_p = false;
   24464 
   24465       /* By default keep the original deduced argument pack.
   24466 	 If necessary, more specific code is going to update the
   24467 	 resulting deduced argument later down in this function.  */
   24468       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
   24469       TMPL_ARG (targs, level, idx) = old_pack;
   24470 
   24471       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
   24472 	 actually deduce anything.  */
   24473       for (i = 0; i < len && !nondeduced_p; ++i)
   24474 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
   24475 	  nondeduced_p = true;
   24476       if (nondeduced_p)
   24477 	continue;
   24478 
   24479       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
   24480         {
   24481           /* If we had fewer function args than explicit template args,
   24482              just use the explicits.  */
   24483           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
   24484           int explicit_len = TREE_VEC_LENGTH (explicit_args);
   24485           if (len < explicit_len)
   24486             new_args = explicit_args;
   24487         }
   24488 
   24489       if (!old_pack)
   24490         {
   24491           tree result;
   24492           /* Build the deduced *_ARGUMENT_PACK.  */
   24493           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
   24494             {
   24495               result = make_node (NONTYPE_ARGUMENT_PACK);
   24496               TREE_CONSTANT (result) = 1;
   24497             }
   24498           else
   24499 	    result = cxx_make_type (TYPE_ARGUMENT_PACK);
   24500 
   24501 	  ARGUMENT_PACK_ARGS (result) = new_args;
   24502 
   24503           /* Note the deduced argument packs for this parameter
   24504              pack.  */
   24505           TMPL_ARG (targs, level, idx) = result;
   24506         }
   24507       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
   24508                && (ARGUMENT_PACK_ARGS (old_pack)
   24509                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
   24510         {
   24511           /* We only had the explicitly-provided arguments before, but
   24512              now we have a complete set of arguments.  */
   24513           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
   24514 
   24515 	  ARGUMENT_PACK_ARGS (old_pack) = new_args;
   24516           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
   24517           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
   24518         }
   24519       else
   24520 	{
   24521 	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
   24522 	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
   24523 	  temp_override<int> ovl (TREE_VEC_LENGTH (old_args));
   24524 	  /* During template argument deduction for the aggregate deduction
   24525 	     candidate, the number of elements in a trailing parameter pack
   24526 	     is only deduced from the number of remaining function
   24527 	     arguments if it is not otherwise deduced.  */
   24528 	  if (cxx_dialect >= cxx20
   24529 	      && TREE_VEC_LENGTH (new_args) < TREE_VEC_LENGTH (old_args)
   24530 	      /* FIXME This isn't set properly for partial instantiations.  */
   24531 	      && TPARMS_PRIMARY_TEMPLATE (tparms)
   24532 	      && builtin_guide_p (TPARMS_PRIMARY_TEMPLATE (tparms)))
   24533 	    TREE_VEC_LENGTH (old_args) = TREE_VEC_LENGTH (new_args);
   24534 	  if (!comp_template_args (old_args, new_args,
   24535 				   &bad_old_arg, &bad_new_arg))
   24536 	    /* Inconsistent unification of this parameter pack.  */
   24537 	    return unify_parameter_pack_inconsistent (explain_p,
   24538 						      bad_old_arg,
   24539 						      bad_new_arg);
   24540 	}
   24541     }
   24542 
   24543   return unify_success (explain_p);
   24544 }
   24545 
   24546 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
   24547    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
   24548    parameters and return value are as for unify.  */
   24549 
   24550 static int
   24551 unify_array_domain (tree tparms, tree targs,
   24552 		    tree parm_dom, tree arg_dom,
   24553 		    bool explain_p)
   24554 {
   24555   tree parm_max;
   24556   tree arg_max;
   24557   bool parm_cst;
   24558   bool arg_cst;
   24559 
   24560   /* Our representation of array types uses "N - 1" as the
   24561      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
   24562      not an integer constant.  We cannot unify arbitrarily
   24563      complex expressions, so we eliminate the MINUS_EXPRs
   24564      here.  */
   24565   parm_max = TYPE_MAX_VALUE (parm_dom);
   24566   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
   24567   if (!parm_cst)
   24568     {
   24569       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
   24570       parm_max = TREE_OPERAND (parm_max, 0);
   24571     }
   24572   arg_max = TYPE_MAX_VALUE (arg_dom);
   24573   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
   24574   if (!arg_cst)
   24575     {
   24576       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
   24577 	 trying to unify the type of a variable with the type
   24578 	 of a template parameter.  For example:
   24579 
   24580 	   template <unsigned int N>
   24581 	   void f (char (&) [N]);
   24582 	   int g();
   24583 	   void h(int i) {
   24584 	     char a[g(i)];
   24585 	     f(a);
   24586 	   }
   24587 
   24588 	 Here, the type of the ARG will be "int [g(i)]", and
   24589 	 may be a SAVE_EXPR, etc.  */
   24590       if (TREE_CODE (arg_max) != MINUS_EXPR)
   24591 	return unify_vla_arg (explain_p, arg_dom);
   24592       arg_max = TREE_OPERAND (arg_max, 0);
   24593     }
   24594 
   24595   /* If only one of the bounds used a MINUS_EXPR, compensate
   24596      by adding one to the other bound.  */
   24597   if (parm_cst && !arg_cst)
   24598     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
   24599 				integer_type_node,
   24600 				parm_max,
   24601 				integer_one_node);
   24602   else if (arg_cst && !parm_cst)
   24603     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
   24604 			       integer_type_node,
   24605 			       arg_max,
   24606 			       integer_one_node);
   24607 
   24608   return unify (tparms, targs, parm_max, arg_max,
   24609 		UNIFY_ALLOW_INTEGER, explain_p);
   24610 }
   24611 
   24612 /* Returns whether T, a P or A in unify, is a type, template or expression.  */
   24613 
   24614 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
   24615 
   24616 static pa_kind_t
   24617 pa_kind (tree t)
   24618 {
   24619   if (PACK_EXPANSION_P (t))
   24620     t = PACK_EXPANSION_PATTERN (t);
   24621   if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
   24622       || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
   24623       || DECL_TYPE_TEMPLATE_P (t))
   24624     return pa_tmpl;
   24625   else if (TYPE_P (t))
   24626     return pa_type;
   24627   else
   24628     return pa_expr;
   24629 }
   24630 
   24631 /* Deduce the value of template parameters.  TPARMS is the (innermost)
   24632    set of template parameters to a template.  TARGS is the bindings
   24633    for those template parameters, as determined thus far; TARGS may
   24634    include template arguments for outer levels of template parameters
   24635    as well.  PARM is a parameter to a template function, or a
   24636    subcomponent of that parameter; ARG is the corresponding argument.
   24637    This function attempts to match PARM with ARG in a manner
   24638    consistent with the existing assignments in TARGS.  If more values
   24639    are deduced, then TARGS is updated.
   24640 
   24641    Returns 0 if the type deduction succeeds, 1 otherwise.  The
   24642    parameter STRICT is a bitwise or of the following flags:
   24643 
   24644      UNIFY_ALLOW_NONE:
   24645        Require an exact match between PARM and ARG.
   24646      UNIFY_ALLOW_MORE_CV_QUAL:
   24647        Allow the deduced ARG to be more cv-qualified (by qualification
   24648        conversion) than ARG.
   24649      UNIFY_ALLOW_LESS_CV_QUAL:
   24650        Allow the deduced ARG to be less cv-qualified than ARG.
   24651      UNIFY_ALLOW_DERIVED:
   24652        Allow the deduced ARG to be a template base class of ARG,
   24653        or a pointer to a template base class of the type pointed to by
   24654        ARG.
   24655      UNIFY_ALLOW_INTEGER:
   24656        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
   24657        case for more information.
   24658      UNIFY_ALLOW_OUTER_LEVEL:
   24659        This is the outermost level of a deduction. Used to determine validity
   24660        of qualification conversions. A valid qualification conversion must
   24661        have const qualified pointers leading up to the inner type which
   24662        requires additional CV quals, except at the outer level, where const
   24663        is not required [conv.qual]. It would be normal to set this flag in
   24664        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
   24665      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
   24666        This is the outermost level of a deduction, and PARM can be more CV
   24667        qualified at this point.
   24668      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
   24669        This is the outermost level of a deduction, and PARM can be less CV
   24670        qualified at this point.  */
   24671 
   24672 static int
   24673 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
   24674        bool explain_p)
   24675 {
   24676   int idx;
   24677   tree targ;
   24678   tree tparm;
   24679   int strict_in = strict;
   24680   tsubst_flags_t complain = (explain_p
   24681 			     ? tf_warning_or_error
   24682 			     : tf_none);
   24683 
   24684   /* I don't think this will do the right thing with respect to types.
   24685      But the only case I've seen it in so far has been array bounds, where
   24686      signedness is the only information lost, and I think that will be
   24687      okay.  VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
   24688      finish_id_expression_1, and are also OK.  */
   24689   while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR
   24690 	 || (TREE_CODE (parm) == IMPLICIT_CONV_EXPR
   24691 	     && IMPLICIT_CONV_EXPR_FORCED (parm)))
   24692     parm = TREE_OPERAND (parm, 0);
   24693 
   24694   if (arg == error_mark_node)
   24695     return unify_invalid (explain_p);
   24696   if (arg == unknown_type_node
   24697       || arg == init_list_type_node)
   24698     /* We can't deduce anything from this, but we might get all the
   24699        template args from other function args.  */
   24700     return unify_success (explain_p);
   24701 
   24702   if (parm == any_targ_node || arg == any_targ_node)
   24703     return unify_success (explain_p);
   24704 
   24705   /* If PARM uses template parameters, then we can't bail out here,
   24706      even if ARG == PARM, since we won't record unifications for the
   24707      template parameters.  We might need them if we're trying to
   24708      figure out which of two things is more specialized.  */
   24709   if (arg == parm
   24710       && (DECL_P (parm) || !uses_template_parms (parm)))
   24711     return unify_success (explain_p);
   24712 
   24713   /* Handle init lists early, so the rest of the function can assume
   24714      we're dealing with a type. */
   24715   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
   24716     {
   24717       tree elttype;
   24718       tree orig_parm = parm;
   24719 
   24720       if (!is_std_init_list (parm)
   24721 	  && TREE_CODE (parm) != ARRAY_TYPE)
   24722 	/* We can only deduce from an initializer list argument if the
   24723 	   parameter is std::initializer_list or an array; otherwise this
   24724 	   is a non-deduced context. */
   24725 	return unify_success (explain_p);
   24726 
   24727       if (TREE_CODE (parm) == ARRAY_TYPE)
   24728 	elttype = TREE_TYPE (parm);
   24729       else
   24730 	{
   24731 	  elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
   24732 	  /* Deduction is defined in terms of a single type, so just punt
   24733 	     on the (bizarre) std::initializer_list<T...>.  */
   24734 	  if (PACK_EXPANSION_P (elttype))
   24735 	    return unify_success (explain_p);
   24736 	}
   24737 
   24738       if (strict != DEDUCE_EXACT
   24739 	  && TYPE_P (elttype)
   24740 	  && !uses_deducible_template_parms (elttype))
   24741 	/* If ELTTYPE has no deducible template parms, skip deduction from
   24742 	   the list elements.  */;
   24743       else
   24744 	for (auto &e: CONSTRUCTOR_ELTS (arg))
   24745 	  {
   24746 	    tree elt = e.value;
   24747 	    int elt_strict = strict;
   24748 
   24749 	    if (elt == error_mark_node)
   24750 	      return unify_invalid (explain_p);
   24751 
   24752 	    if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
   24753 	      {
   24754 		tree type = TREE_TYPE (elt);
   24755 		if (type == error_mark_node)
   24756 		  return unify_invalid (explain_p);
   24757 		/* It should only be possible to get here for a call.  */
   24758 		gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
   24759 		elt_strict |= maybe_adjust_types_for_deduction
   24760 		  (tparms, DEDUCE_CALL, &elttype, &type, elt);
   24761 		elt = type;
   24762 	      }
   24763 
   24764 	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
   24765 				   explain_p);
   24766 	}
   24767 
   24768       if (TREE_CODE (parm) == ARRAY_TYPE
   24769 	  && deducible_array_bound (TYPE_DOMAIN (parm)))
   24770 	{
   24771 	  /* Also deduce from the length of the initializer list.  */
   24772 	  tree max = size_int (CONSTRUCTOR_NELTS (arg));
   24773 	  tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
   24774 	  if (idx == error_mark_node)
   24775 	    return unify_invalid (explain_p);
   24776 	  return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
   24777 				     idx, explain_p);
   24778 	}
   24779 
   24780       /* If the std::initializer_list<T> deduction worked, replace the
   24781 	 deduced A with std::initializer_list<A>.  */
   24782       if (orig_parm != parm)
   24783 	{
   24784 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
   24785 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
   24786 	  targ = listify (targ);
   24787 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
   24788 	}
   24789       return unify_success (explain_p);
   24790     }
   24791 
   24792   /* If parm and arg aren't the same kind of thing (template, type, or
   24793      expression), fail early.  */
   24794   if (pa_kind (parm) != pa_kind (arg))
   24795     return unify_invalid (explain_p);
   24796 
   24797   /* Immediately reject some pairs that won't unify because of
   24798      cv-qualification mismatches.  */
   24799   if (TREE_CODE (arg) == TREE_CODE (parm)
   24800       && TYPE_P (arg)
   24801       /* It is the elements of the array which hold the cv quals of an array
   24802 	 type, and the elements might be template type parms. We'll check
   24803 	 when we recurse.  */
   24804       && TREE_CODE (arg) != ARRAY_TYPE
   24805       /* We check the cv-qualifiers when unifying with template type
   24806 	 parameters below.  We want to allow ARG `const T' to unify with
   24807 	 PARM `T' for example, when computing which of two templates
   24808 	 is more specialized, for example.  */
   24809       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
   24810       && !check_cv_quals_for_unify (strict_in, arg, parm))
   24811     return unify_cv_qual_mismatch (explain_p, parm, arg);
   24812 
   24813   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
   24814       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm)
   24815       && !FUNC_OR_METHOD_TYPE_P (parm))
   24816     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
   24817   /* PMFs recurse at the same level, so don't strip this yet.  */
   24818   if (!TYPE_PTRMEMFUNC_P (parm))
   24819     strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
   24820   strict &= ~UNIFY_ALLOW_DERIVED;
   24821   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
   24822   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
   24823 
   24824   switch (TREE_CODE (parm))
   24825     {
   24826     case TYPENAME_TYPE:
   24827     case SCOPE_REF:
   24828     case UNBOUND_CLASS_TEMPLATE:
   24829       /* In a type which contains a nested-name-specifier, template
   24830 	 argument values cannot be deduced for template parameters used
   24831 	 within the nested-name-specifier.  */
   24832       return unify_success (explain_p);
   24833 
   24834     case TEMPLATE_TYPE_PARM:
   24835     case TEMPLATE_TEMPLATE_PARM:
   24836     case BOUND_TEMPLATE_TEMPLATE_PARM:
   24837       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
   24838       if (error_operand_p (tparm))
   24839 	return unify_invalid (explain_p);
   24840 
   24841       if (TEMPLATE_TYPE_LEVEL (parm)
   24842 	  != template_decl_level (tparm))
   24843 	/* The PARM is not one we're trying to unify.  Just check
   24844 	   to see if it matches ARG.  */
   24845 	{
   24846 	  if (TREE_CODE (arg) == TREE_CODE (parm)
   24847 	      && (is_auto (parm) ? is_auto (arg)
   24848 		  : same_type_p (parm, arg)))
   24849 	    return unify_success (explain_p);
   24850 	  else
   24851 	    return unify_type_mismatch (explain_p, parm, arg);
   24852 	}
   24853       idx = TEMPLATE_TYPE_IDX (parm);
   24854       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
   24855       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
   24856       if (error_operand_p (tparm))
   24857 	return unify_invalid (explain_p);
   24858 
   24859       /* Check for mixed types and values.  */
   24860       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
   24861 	   && TREE_CODE (tparm) != TYPE_DECL)
   24862 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
   24863 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
   24864 	gcc_unreachable ();
   24865 
   24866       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
   24867 	{
   24868 	  if ((strict_in & UNIFY_ALLOW_DERIVED)
   24869 	      && CLASS_TYPE_P (arg))
   24870 	    {
   24871 	      /* First try to match ARG directly.  */
   24872 	      tree t = try_class_unification (tparms, targs, parm, arg,
   24873 					      explain_p);
   24874 	      if (!t)
   24875 		{
   24876 		  /* Otherwise, look for a suitable base of ARG, as below.  */
   24877 		  enum template_base_result r;
   24878 		  r = get_template_base (tparms, targs, parm, arg,
   24879 					 explain_p, &t);
   24880 		  if (!t)
   24881 		    return unify_no_common_base (explain_p, r, parm, arg);
   24882 		  arg = t;
   24883 		}
   24884 	    }
   24885 	  /* ARG must be constructed from a template class or a template
   24886 	     template parameter.  */
   24887 	  else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
   24888 		   && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
   24889 	    return unify_template_deduction_failure (explain_p, parm, arg);
   24890 
   24891 	  /* Deduce arguments T, i from TT<T> or TT<i>.  */
   24892 	  if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
   24893 	    return 1;
   24894 
   24895 	  arg = TYPE_TI_TEMPLATE (arg);
   24896 	  if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
   24897 	    /* If the template is a template template parameter, use the
   24898 	       TEMPLATE_TEMPLATE_PARM for matching.  */
   24899 	    arg = TREE_TYPE (arg);
   24900 
   24901 	  /* Fall through to deduce template name.  */
   24902 	}
   24903 
   24904       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
   24905 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
   24906 	{
   24907 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
   24908 
   24909 	  /* Simple cases: Value already set, does match or doesn't.  */
   24910 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
   24911 	    return unify_success (explain_p);
   24912 	  else if (targ)
   24913 	    return unify_inconsistency (explain_p, parm, targ, arg);
   24914 	}
   24915       else
   24916 	{
   24917 	  /* If PARM is `const T' and ARG is only `int', we don't have
   24918 	     a match unless we are allowing additional qualification.
   24919 	     If ARG is `const int' and PARM is just `T' that's OK;
   24920 	     that binds `const int' to `T'.  */
   24921 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
   24922 					 arg, parm))
   24923 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
   24924 
   24925 	  /* Consider the case where ARG is `const volatile int' and
   24926 	     PARM is `const T'.  Then, T should be `volatile int'.  */
   24927 	  arg = cp_build_qualified_type
   24928 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
   24929 	  if (arg == error_mark_node)
   24930 	    return unify_invalid (explain_p);
   24931 
   24932 	  /* Simple cases: Value already set, does match or doesn't.  */
   24933 	  if (targ != NULL_TREE && same_type_p (targ, arg))
   24934 	    return unify_success (explain_p);
   24935 	  else if (targ)
   24936 	    return unify_inconsistency (explain_p, parm, targ, arg);
   24937 
   24938 	  /* Make sure that ARG is not a variable-sized array.  (Note
   24939 	     that were talking about variable-sized arrays (like
   24940 	     `int[n]'), rather than arrays of unknown size (like
   24941 	     `int[]').)  We'll get very confused by such a type since
   24942 	     the bound of the array is not constant, and therefore
   24943 	     not mangleable.  Besides, such types are not allowed in
   24944 	     ISO C++, so we can do as we please here.  We do allow
   24945 	     them for 'auto' deduction, since that isn't ABI-exposed.  */
   24946 	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
   24947 	    return unify_vla_arg (explain_p, arg);
   24948 
   24949 	  /* Strip typedefs as in convert_template_argument.  */
   24950 	  arg = canonicalize_type_argument (arg, tf_none);
   24951 	}
   24952 
   24953       /* If ARG is a parameter pack or an expansion, we cannot unify
   24954 	 against it unless PARM is also a parameter pack.  */
   24955       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
   24956 	  && !template_parameter_pack_p (parm))
   24957 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
   24958 
   24959       /* If the argument deduction results is a METHOD_TYPE,
   24960          then there is a problem.
   24961          METHOD_TYPE doesn't map to any real C++ type the result of
   24962 	 the deduction cannot be of that type.  */
   24963       if (TREE_CODE (arg) == METHOD_TYPE)
   24964 	return unify_method_type_error (explain_p, arg);
   24965 
   24966       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
   24967       return unify_success (explain_p);
   24968 
   24969     case TEMPLATE_PARM_INDEX:
   24970       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
   24971       if (error_operand_p (tparm))
   24972 	return unify_invalid (explain_p);
   24973 
   24974       if (TEMPLATE_PARM_LEVEL (parm)
   24975 	  != template_decl_level (tparm))
   24976 	{
   24977 	  /* The PARM is not one we're trying to unify.  Just check
   24978 	     to see if it matches ARG.  */
   24979 	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
   24980 			 && cp_tree_equal (parm, arg));
   24981 	  if (result)
   24982 	    unify_expression_unequal (explain_p, parm, arg);
   24983 	  return result;
   24984 	}
   24985 
   24986       idx = TEMPLATE_PARM_IDX (parm);
   24987       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
   24988 
   24989       if (targ)
   24990 	{
   24991 	  if ((strict & UNIFY_ALLOW_INTEGER)
   24992 	      && TREE_TYPE (targ) && TREE_TYPE (arg)
   24993 	      && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
   24994 	    /* We're deducing from an array bound, the type doesn't matter.
   24995 	       This conversion should match the one below.  */
   24996 	    arg = fold (build_nop (TREE_TYPE (targ), arg));
   24997 	  int x = !cp_tree_equal (targ, arg);
   24998 	  if (x)
   24999 	    unify_inconsistency (explain_p, parm, targ, arg);
   25000 	  return x;
   25001 	}
   25002 
   25003       /* [temp.deduct.type] If, in the declaration of a function template
   25004 	 with a non-type template-parameter, the non-type
   25005 	 template-parameter is used in an expression in the function
   25006 	 parameter-list and, if the corresponding template-argument is
   25007 	 deduced, the template-argument type shall match the type of the
   25008 	 template-parameter exactly, except that a template-argument
   25009 	 deduced from an array bound may be of any integral type.
   25010 	 The non-type parameter might use already deduced type parameters.  */
   25011       tparm = TREE_TYPE (parm);
   25012       if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
   25013 	/* We don't have enough levels of args to do any substitution.  This
   25014 	   can happen in the context of -fnew-ttp-matching.  */;
   25015       else
   25016 	{
   25017 	  ++processing_template_decl;
   25018 	  tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
   25019 	  --processing_template_decl;
   25020 
   25021 	  if (tree a = type_uses_auto (tparm))
   25022 	    {
   25023 	      tparm = do_auto_deduction (tparm, arg, a,
   25024 					 complain, adc_unify, targs,
   25025 					 LOOKUP_NORMAL,
   25026 					 TPARMS_PRIMARY_TEMPLATE (tparms));
   25027 	      if (tparm == error_mark_node)
   25028 		return 1;
   25029 	    }
   25030 	}
   25031 
   25032       if (!TREE_TYPE (arg)
   25033 	  || TREE_CODE (TREE_TYPE (arg)) == DEPENDENT_OPERATOR_TYPE)
   25034 	/* Template-parameter dependent expression.  Just accept it for now.
   25035 	   It will later be processed in convert_template_argument.  */
   25036 	;
   25037       else if (same_type_ignoring_top_level_qualifiers_p
   25038 	       (non_reference (TREE_TYPE (arg)),
   25039 		non_reference (tparm)))
   25040 	/* OK.  Ignore top-level quals here because a class-type template
   25041 	   parameter object is const.  */;
   25042       else if ((strict & UNIFY_ALLOW_INTEGER)
   25043 	       && CP_INTEGRAL_TYPE_P (tparm))
   25044 	/* Convert the ARG to the type of PARM; the deduced non-type
   25045 	   template argument must exactly match the types of the
   25046 	   corresponding parameter.  This conversion should match the
   25047 	   one above.  */
   25048 	arg = fold (build_nop (tparm, arg));
   25049       else if (uses_template_parms (tparm))
   25050 	{
   25051 	  /* We haven't deduced the type of this parameter yet.  */
   25052 	  if (cxx_dialect >= cxx17
   25053 	      /* We deduce from array bounds in try_array_deduction.  */
   25054 	      && !(strict & UNIFY_ALLOW_INTEGER)
   25055 	      && TEMPLATE_PARM_LEVEL (parm) <= TMPL_ARGS_DEPTH (targs))
   25056 	    {
   25057 	      /* Deduce it from the non-type argument.  As above, ignore
   25058 		 top-level quals here too.  */
   25059 	      tree atype = cv_unqualified (TREE_TYPE (arg));
   25060 	      RECUR_AND_CHECK_FAILURE (tparms, targs,
   25061 				       tparm, atype,
   25062 				       UNIFY_ALLOW_NONE, explain_p);
   25063 	      /* Now check whether the type of this parameter is still
   25064 		 dependent, and give up if so.  */
   25065 	      ++processing_template_decl;
   25066 	      tparm = tsubst (TREE_TYPE (parm), targs, tf_none, NULL_TREE);
   25067 	      --processing_template_decl;
   25068 	      if (uses_template_parms (tparm))
   25069 		return unify_success (explain_p);
   25070 	    }
   25071 	  else
   25072 	    /* Try again later.  */
   25073 	    return unify_success (explain_p);
   25074 	}
   25075       else
   25076 	return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
   25077 
   25078       /* If ARG is a parameter pack or an expansion, we cannot unify
   25079 	 against it unless PARM is also a parameter pack.  */
   25080       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
   25081 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
   25082 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
   25083 
   25084       {
   25085 	bool removed_attr = false;
   25086 	arg = strip_typedefs_expr (arg, &removed_attr);
   25087       }
   25088       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
   25089       return unify_success (explain_p);
   25090 
   25091     case PTRMEM_CST:
   25092      {
   25093 	/* A pointer-to-member constant can be unified only with
   25094 	 another constant.  */
   25095       if (TREE_CODE (arg) != PTRMEM_CST)
   25096 	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
   25097 
   25098       /* Just unify the class member. It would be useless (and possibly
   25099 	 wrong, depending on the strict flags) to unify also
   25100 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
   25101 	 arg refer to the same variable, even if through different
   25102 	 classes. For instance:
   25103 
   25104 	 struct A { int x; };
   25105 	 struct B : A { };
   25106 
   25107 	 Unification of &A::x and &B::x must succeed.  */
   25108       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
   25109 		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
   25110      }
   25111 
   25112     case POINTER_TYPE:
   25113       {
   25114 	if (!TYPE_PTR_P (arg))
   25115 	  return unify_type_mismatch (explain_p, parm, arg);
   25116 
   25117 	/* [temp.deduct.call]
   25118 
   25119 	   A can be another pointer or pointer to member type that can
   25120 	   be converted to the deduced A via a qualification
   25121 	   conversion (_conv.qual_).
   25122 
   25123 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
   25124 	   This will allow for additional cv-qualification of the
   25125 	   pointed-to types if appropriate.  */
   25126 
   25127 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
   25128 	  /* The derived-to-base conversion only persists through one
   25129 	     level of pointers.  */
   25130 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
   25131 
   25132 	return unify (tparms, targs, TREE_TYPE (parm),
   25133 		      TREE_TYPE (arg), strict, explain_p);
   25134       }
   25135 
   25136     case REFERENCE_TYPE:
   25137       if (!TYPE_REF_P (arg))
   25138 	return unify_type_mismatch (explain_p, parm, arg);
   25139       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
   25140 		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
   25141 
   25142     case ARRAY_TYPE:
   25143       if (TREE_CODE (arg) != ARRAY_TYPE)
   25144 	return unify_type_mismatch (explain_p, parm, arg);
   25145       if ((TYPE_DOMAIN (parm) == NULL_TREE)
   25146 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
   25147 	return unify_type_mismatch (explain_p, parm, arg);
   25148       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
   25149 			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
   25150       if (TYPE_DOMAIN (parm) != NULL_TREE)
   25151 	return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
   25152 				   TYPE_DOMAIN (arg), explain_p);
   25153       return unify_success (explain_p);
   25154 
   25155     case REAL_TYPE:
   25156     case COMPLEX_TYPE:
   25157     case VECTOR_TYPE:
   25158     case INTEGER_TYPE:
   25159     case BOOLEAN_TYPE:
   25160     case ENUMERAL_TYPE:
   25161     case VOID_TYPE:
   25162     case OPAQUE_TYPE:
   25163     case NULLPTR_TYPE:
   25164       if (TREE_CODE (arg) != TREE_CODE (parm))
   25165 	return unify_type_mismatch (explain_p, parm, arg);
   25166 
   25167       /* We have already checked cv-qualification at the top of the
   25168 	 function.  */
   25169       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
   25170 	return unify_type_mismatch (explain_p, parm, arg);
   25171 
   25172       /* As far as unification is concerned, this wins.	 Later checks
   25173 	 will invalidate it if necessary.  */
   25174       return unify_success (explain_p);
   25175 
   25176       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
   25177       /* Type INTEGER_CST can come from ordinary constant template args.  */
   25178     case INTEGER_CST:
   25179     case REAL_CST:
   25180       if (TREE_TYPE (arg) == NULL_TREE
   25181 	  || !same_type_p (TREE_TYPE (parm), TREE_TYPE (arg)))
   25182 	return unify_template_argument_mismatch (explain_p, parm, arg);
   25183       while (CONVERT_EXPR_P (arg))
   25184 	arg = TREE_OPERAND (arg, 0);
   25185 
   25186       if (TREE_CODE (arg) != TREE_CODE (parm))
   25187 	return unify_template_argument_mismatch (explain_p, parm, arg);
   25188       return (simple_cst_equal (parm, arg)
   25189 	      ? unify_success (explain_p)
   25190 	      : unify_template_argument_mismatch (explain_p, parm, arg));
   25191 
   25192     case TREE_VEC:
   25193       {
   25194 	int i, len, argslen;
   25195 	int parm_variadic_p = 0;
   25196 
   25197 	if (TREE_CODE (arg) != TREE_VEC)
   25198 	  return unify_template_argument_mismatch (explain_p, parm, arg);
   25199 
   25200 	len = TREE_VEC_LENGTH (parm);
   25201 	argslen = TREE_VEC_LENGTH (arg);
   25202 
   25203 	/* Check for pack expansions in the parameters.  */
   25204 	for (i = 0; i < len; ++i)
   25205 	  {
   25206 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
   25207 	      {
   25208 		if (i == len - 1)
   25209 		  /* We can unify against something with a trailing
   25210 		     parameter pack.  */
   25211 		  parm_variadic_p = 1;
   25212 		else
   25213 		  /* [temp.deduct.type]/9: If the template argument list of
   25214 		     P contains a pack expansion that is not the last
   25215 		     template argument, the entire template argument list
   25216 		     is a non-deduced context.  */
   25217 		  return unify_success (explain_p);
   25218 	      }
   25219 	  }
   25220 
   25221         /* If we don't have enough arguments to satisfy the parameters
   25222            (not counting the pack expression at the end), or we have
   25223            too many arguments for a parameter list that doesn't end in
   25224            a pack expression, we can't unify.  */
   25225 	if (parm_variadic_p
   25226 	    ? argslen < len - parm_variadic_p
   25227 	    : argslen != len)
   25228 	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
   25229 
   25230 	/* Unify all of the parameters that precede the (optional)
   25231 	   pack expression.  */
   25232 	for (i = 0; i < len - parm_variadic_p; ++i)
   25233 	  {
   25234 	    RECUR_AND_CHECK_FAILURE (tparms, targs,
   25235 				     TREE_VEC_ELT (parm, i),
   25236 				     TREE_VEC_ELT (arg, i),
   25237 				     UNIFY_ALLOW_NONE, explain_p);
   25238 	  }
   25239 	if (parm_variadic_p)
   25240 	  return unify_pack_expansion (tparms, targs, parm, arg,
   25241 				       DEDUCE_EXACT,
   25242 				       /*subr=*/true, explain_p);
   25243 	return unify_success (explain_p);
   25244       }
   25245 
   25246     case RECORD_TYPE:
   25247     case UNION_TYPE:
   25248       if (TREE_CODE (arg) != TREE_CODE (parm))
   25249 	return unify_type_mismatch (explain_p, parm, arg);
   25250 
   25251       if (TYPE_PTRMEMFUNC_P (parm))
   25252 	{
   25253 	  if (!TYPE_PTRMEMFUNC_P (arg))
   25254 	    return unify_type_mismatch (explain_p, parm, arg);
   25255 
   25256 	  return unify (tparms, targs,
   25257 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
   25258 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
   25259 			strict, explain_p);
   25260 	}
   25261       else if (TYPE_PTRMEMFUNC_P (arg))
   25262 	return unify_type_mismatch (explain_p, parm, arg);
   25263 
   25264       if (CLASSTYPE_TEMPLATE_INFO (parm))
   25265 	{
   25266 	  tree t = NULL_TREE;
   25267 
   25268 	  if (strict_in & UNIFY_ALLOW_DERIVED)
   25269 	    {
   25270 	      /* First, we try to unify the PARM and ARG directly.  */
   25271 	      t = try_class_unification (tparms, targs,
   25272 					 parm, arg, explain_p);
   25273 
   25274 	      if (!t)
   25275 		{
   25276 		  /* Fallback to the special case allowed in
   25277 		     [temp.deduct.call]:
   25278 
   25279 		       If P is a class, and P has the form
   25280 		       template-id, then A can be a derived class of
   25281 		       the deduced A.  Likewise, if P is a pointer to
   25282 		       a class of the form template-id, A can be a
   25283 		       pointer to a derived class pointed to by the
   25284 		       deduced A.  */
   25285 		  enum template_base_result r;
   25286 		  r = get_template_base (tparms, targs, parm, arg,
   25287 					 explain_p, &t);
   25288 
   25289 		  if (!t)
   25290 		    {
   25291 		      /* Don't give the derived diagnostic if we're
   25292 			 already dealing with the same template.  */
   25293 		      bool same_template
   25294 			= (CLASSTYPE_TEMPLATE_INFO (arg)
   25295 			   && (CLASSTYPE_TI_TEMPLATE (parm)
   25296 			       == CLASSTYPE_TI_TEMPLATE (arg)));
   25297 		      return unify_no_common_base (explain_p && !same_template,
   25298 						   r, parm, arg);
   25299 		    }
   25300 		}
   25301 	    }
   25302 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
   25303 		   && (CLASSTYPE_TI_TEMPLATE (parm)
   25304 		       == CLASSTYPE_TI_TEMPLATE (arg)))
   25305 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
   25306 	       Then, we should unify `int' and `U'.  */
   25307 	    t = arg;
   25308 	  else
   25309 	    /* There's no chance of unification succeeding.  */
   25310 	    return unify_type_mismatch (explain_p, parm, arg);
   25311 
   25312 	  if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)))
   25313 	    return unify (tparms, targs,
   25314 			  INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (parm)),
   25315 			  INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (t)),
   25316 			  UNIFY_ALLOW_NONE, explain_p);
   25317 	  gcc_checking_assert (t == arg);
   25318 	}
   25319 
   25320       if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
   25321 	return unify_type_mismatch (explain_p, parm, arg);
   25322       return unify_success (explain_p);
   25323 
   25324     case METHOD_TYPE:
   25325     case FUNCTION_TYPE:
   25326       {
   25327 	unsigned int nargs;
   25328 	tree *args;
   25329 	tree a;
   25330 	unsigned int i;
   25331 
   25332 	if (TREE_CODE (arg) != TREE_CODE (parm))
   25333 	  return unify_type_mismatch (explain_p, parm, arg);
   25334 
   25335 	/* CV qualifications for methods can never be deduced, they must
   25336 	   match exactly.  We need to check them explicitly here,
   25337 	   because type_unification_real treats them as any other
   25338 	   cv-qualified parameter.  */
   25339 	if (TREE_CODE (parm) == METHOD_TYPE
   25340 	    && (!check_cv_quals_for_unify
   25341 		(UNIFY_ALLOW_NONE,
   25342 		 class_of_this_parm (arg),
   25343 		 class_of_this_parm (parm))))
   25344 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
   25345 	if (TREE_CODE (arg) == FUNCTION_TYPE
   25346 	    && type_memfn_quals (parm) != type_memfn_quals (arg))
   25347 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
   25348 	if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
   25349 	  return unify_type_mismatch (explain_p, parm, arg);
   25350 
   25351 	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
   25352 				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
   25353 
   25354 	nargs = list_length (TYPE_ARG_TYPES (arg));
   25355 	args = XALLOCAVEC (tree, nargs);
   25356 	for (a = TYPE_ARG_TYPES (arg), i = 0;
   25357 	     a != NULL_TREE && a != void_list_node;
   25358 	     a = TREE_CHAIN (a), ++i)
   25359 	  args[i] = TREE_VALUE (a);
   25360 	nargs = i;
   25361 
   25362 	if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
   25363 				   args, nargs, 1, DEDUCE_EXACT,
   25364 				   NULL, explain_p))
   25365 	  return 1;
   25366 
   25367 	if (flag_noexcept_type)
   25368 	  {
   25369 	    tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
   25370 	    tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
   25371 	    if (pspec == NULL_TREE) pspec = noexcept_false_spec;
   25372 	    if (aspec == NULL_TREE) aspec = noexcept_false_spec;
   25373 	    if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
   25374 		&& uses_template_parms (TREE_PURPOSE (pspec)))
   25375 	      RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
   25376 				       TREE_PURPOSE (aspec),
   25377 				       UNIFY_ALLOW_NONE, explain_p);
   25378 	    else
   25379 	      {
   25380 		bool pn = nothrow_spec_p (pspec);
   25381 		bool an = nothrow_spec_p (aspec);
   25382 		/* Here "less cv-qual" means the deduced arg (i.e. parm) has
   25383 		   /more/ noexcept, since function pointer conversions are the
   25384 		   reverse of qualification conversions.  */
   25385 		if (an == pn
   25386 		    || (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
   25387 		    || (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
   25388 		  /* OK.  */;
   25389 		else
   25390 		  return unify_type_mismatch (explain_p, parm, arg);
   25391 	      }
   25392 	  }
   25393 	if (flag_tm)
   25394 	  {
   25395 	    /* As for noexcept.  */
   25396 	    bool pn = tx_safe_fn_type_p (parm);
   25397 	    bool an = tx_safe_fn_type_p (arg);
   25398 	    if (an == pn
   25399 		|| (an < pn && (strict & UNIFY_ALLOW_LESS_CV_QUAL))
   25400 		|| (an > pn && (strict & UNIFY_ALLOW_MORE_CV_QUAL)))
   25401 	      /* OK.  */;
   25402 	    else
   25403 	      return unify_type_mismatch (explain_p, parm, arg);
   25404 	  }
   25405 
   25406 	return 0;
   25407       }
   25408 
   25409     case OFFSET_TYPE:
   25410       /* Unify a pointer to member with a pointer to member function, which
   25411 	 deduces the type of the member as a function type. */
   25412       if (TYPE_PTRMEMFUNC_P (arg))
   25413 	{
   25414 	  /* Check top-level cv qualifiers */
   25415 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
   25416 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
   25417 
   25418 	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
   25419 				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
   25420 				   UNIFY_ALLOW_NONE, explain_p);
   25421 
   25422 	  /* Determine the type of the function we are unifying against. */
   25423 	  tree fntype = static_fn_type (arg);
   25424 
   25425 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
   25426 	}
   25427 
   25428       if (TREE_CODE (arg) != OFFSET_TYPE)
   25429 	return unify_type_mismatch (explain_p, parm, arg);
   25430       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
   25431 			       TYPE_OFFSET_BASETYPE (arg),
   25432 			       UNIFY_ALLOW_NONE, explain_p);
   25433       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
   25434 		    strict, explain_p);
   25435 
   25436     case CONST_DECL:
   25437       /* CONST_DECL should already have been folded to its DECL_INITIAL.  */
   25438       gcc_unreachable ();
   25439 
   25440     case FIELD_DECL:
   25441     case FUNCTION_DECL:
   25442     case TEMPLATE_DECL:
   25443       /* Matched cases are handled by the ARG == PARM test above.  */
   25444       return unify_template_argument_mismatch (explain_p, parm, arg);
   25445 
   25446     case VAR_DECL:
   25447       /* We might get a variable as a non-type template argument in parm if the
   25448 	 corresponding parameter is type-dependent.  Make any necessary
   25449 	 adjustments based on whether arg is a reference.  */
   25450       if (CONSTANT_CLASS_P (arg))
   25451 	parm = fold_non_dependent_expr (parm, complain);
   25452       else if (REFERENCE_REF_P (arg))
   25453 	{
   25454 	  tree sub = TREE_OPERAND (arg, 0);
   25455 	  STRIP_NOPS (sub);
   25456 	  if (TREE_CODE (sub) == ADDR_EXPR)
   25457 	    arg = TREE_OPERAND (sub, 0);
   25458 	}
   25459       /* Now use the normal expression code to check whether they match.  */
   25460       goto expr;
   25461 
   25462     case TYPE_ARGUMENT_PACK:
   25463     case NONTYPE_ARGUMENT_PACK:
   25464       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
   25465 		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
   25466 
   25467     case TYPEOF_TYPE:
   25468     case DECLTYPE_TYPE:
   25469     case TRAIT_TYPE:
   25470       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
   25471 	 or TRAIT_TYPE nodes.  */
   25472       return unify_success (explain_p);
   25473 
   25474     case ERROR_MARK:
   25475       /* Unification fails if we hit an error node.  */
   25476       return unify_invalid (explain_p);
   25477 
   25478     case INDIRECT_REF:
   25479       if (REFERENCE_REF_P (parm))
   25480 	{
   25481 	  bool pexp = PACK_EXPANSION_P (arg);
   25482 	  if (pexp)
   25483 	    arg = PACK_EXPANSION_PATTERN (arg);
   25484 	  if (REFERENCE_REF_P (arg))
   25485 	    arg = TREE_OPERAND (arg, 0);
   25486 	  if (pexp)
   25487 	    arg = make_pack_expansion (arg, complain);
   25488 	  return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
   25489 			strict, explain_p);
   25490 	}
   25491       /* FALLTHRU */
   25492 
   25493     default:
   25494       /* An unresolved overload is a nondeduced context.  */
   25495       if (is_overloaded_fn (parm) || type_unknown_p (parm))
   25496 	return unify_success (explain_p);
   25497       gcc_assert (EXPR_P (parm)
   25498 		  || TREE_CODE (parm) == CONSTRUCTOR
   25499 		  || TREE_CODE (parm) == TRAIT_EXPR);
   25500     expr:
   25501       /* We must be looking at an expression.  This can happen with
   25502 	 something like:
   25503 
   25504 	   template <int I>
   25505 	   void foo(S<I>, S<I + 2>);
   25506 
   25507 	 or
   25508 
   25509 	   template<typename T>
   25510 	   void foo(A<T, T{}>);
   25511 
   25512 	 This is a "non-deduced context":
   25513 
   25514 	   [deduct.type]
   25515 
   25516 	   The non-deduced contexts are:
   25517 
   25518 	   --A non-type template argument or an array bound in which
   25519 	     a subexpression references a template parameter.
   25520 
   25521 	 In these cases, we assume deduction succeeded, but don't
   25522 	 actually infer any unifications.  */
   25523 
   25524       if (!uses_template_parms (parm)
   25525 	  && !template_args_equal (parm, arg))
   25526 	return unify_expression_unequal (explain_p, parm, arg);
   25527       else
   25528 	return unify_success (explain_p);
   25529     }
   25530 }
   25531 #undef RECUR_AND_CHECK_FAILURE
   25532 
   25533 /* Note that DECL can be defined in this translation unit, if
   25535    required.  */
   25536 
   25537 static void
   25538 mark_definable (tree decl)
   25539 {
   25540   tree clone;
   25541   DECL_NOT_REALLY_EXTERN (decl) = 1;
   25542   FOR_EACH_CLONE (clone, decl)
   25543     DECL_NOT_REALLY_EXTERN (clone) = 1;
   25544 }
   25545 
   25546 /* Called if RESULT is explicitly instantiated, or is a member of an
   25547    explicitly instantiated class.  */
   25548 
   25549 void
   25550 mark_decl_instantiated (tree result, int extern_p)
   25551 {
   25552   SET_DECL_EXPLICIT_INSTANTIATION (result);
   25553 
   25554   /* If this entity has already been written out, it's too late to
   25555      make any modifications.  */
   25556   if (TREE_ASM_WRITTEN (result))
   25557     return;
   25558 
   25559   /* consteval functions are never emitted.  */
   25560   if (TREE_CODE (result) == FUNCTION_DECL
   25561       && DECL_IMMEDIATE_FUNCTION_P (result))
   25562     return;
   25563 
   25564   /* For anonymous namespace we don't need to do anything.  */
   25565   if (decl_internal_context_p (result))
   25566     {
   25567       gcc_assert (!TREE_PUBLIC (result));
   25568       return;
   25569     }
   25570 
   25571   if (TREE_CODE (result) != FUNCTION_DECL)
   25572     /* The TREE_PUBLIC flag for function declarations will have been
   25573        set correctly by tsubst.  */
   25574     TREE_PUBLIC (result) = 1;
   25575 
   25576   if (extern_p)
   25577     {
   25578       DECL_EXTERNAL (result) = 1;
   25579       DECL_NOT_REALLY_EXTERN (result) = 0;
   25580     }
   25581   else
   25582     {
   25583       mark_definable (result);
   25584       mark_needed (result);
   25585       /* Always make artificials weak.  */
   25586       if (DECL_ARTIFICIAL (result) && flag_weak)
   25587 	comdat_linkage (result);
   25588       /* For WIN32 we also want to put explicit instantiations in
   25589 	 linkonce sections.  */
   25590       else if (TREE_PUBLIC (result))
   25591 	maybe_make_one_only (result);
   25592       if (TREE_CODE (result) == FUNCTION_DECL
   25593 	  && DECL_TEMPLATE_INSTANTIATED (result))
   25594 	/* If the function has already been instantiated, clear DECL_EXTERNAL,
   25595 	   since start_preparsed_function wouldn't have if we had an earlier
   25596 	   extern explicit instantiation.  */
   25597 	DECL_EXTERNAL (result) = 0;
   25598     }
   25599 
   25600   /* If EXTERN_P, then this function will not be emitted -- unless
   25601      followed by an explicit instantiation, at which point its linkage
   25602      will be adjusted.  If !EXTERN_P, then this function will be
   25603      emitted here.  In neither circumstance do we want
   25604      import_export_decl to adjust the linkage.  */
   25605   DECL_INTERFACE_KNOWN (result) = 1;
   25606 }
   25607 
   25608 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
   25609    important template arguments.  If any are missing, we check whether
   25610    they're important by using error_mark_node for substituting into any
   25611    args that were used for partial ordering (the ones between ARGS and END)
   25612    and seeing if it bubbles up.  */
   25613 
   25614 static bool
   25615 check_undeduced_parms (tree targs, tree args, tree end)
   25616 {
   25617   bool found = false;
   25618   for (tree& targ : tree_vec_range (targs))
   25619     if (targ == NULL_TREE)
   25620       {
   25621 	found = true;
   25622 	targ = error_mark_node;
   25623       }
   25624   if (found)
   25625     {
   25626       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
   25627       if (substed == error_mark_node)
   25628 	return true;
   25629     }
   25630   return false;
   25631 }
   25632 
   25633 /* Given two function templates PAT1 and PAT2, return:
   25634 
   25635    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
   25636    -1 if PAT2 is more specialized than PAT1.
   25637    0 if neither is more specialized.
   25638 
   25639    LEN indicates the number of parameters we should consider
   25640    (defaulted parameters should not be considered).
   25641 
   25642    The 1998 std underspecified function template partial ordering, and
   25643    DR214 addresses the issue.  We take pairs of arguments, one from
   25644    each of the templates, and deduce them against each other.  One of
   25645    the templates will be more specialized if all the *other*
   25646    template's arguments deduce against its arguments and at least one
   25647    of its arguments *does* *not* deduce against the other template's
   25648    corresponding argument.  Deduction is done as for class templates.
   25649    The arguments used in deduction have reference and top level cv
   25650    qualifiers removed.  Iff both arguments were originally reference
   25651    types *and* deduction succeeds in both directions, an lvalue reference
   25652    wins against an rvalue reference and otherwise the template
   25653    with the more cv-qualified argument wins for that pairing (if
   25654    neither is more cv-qualified, they both are equal).  Unlike regular
   25655    deduction, after all the arguments have been deduced in this way,
   25656    we do *not* verify the deduced template argument values can be
   25657    substituted into non-deduced contexts.
   25658 
   25659    The logic can be a bit confusing here, because we look at deduce1 and
   25660    targs1 to see if pat2 is at least as specialized, and vice versa; if we
   25661    can find template arguments for pat1 to make arg1 look like arg2, that
   25662    means that arg2 is at least as specialized as arg1.  */
   25663 
   25664 int
   25665 more_specialized_fn (tree pat1, tree pat2, int len)
   25666 {
   25667   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
   25668   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
   25669   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
   25670   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
   25671   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
   25672   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
   25673   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
   25674   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
   25675   tree origs1, origs2;
   25676   bool lose1 = false;
   25677   bool lose2 = false;
   25678 
   25679   /* C++17 [temp.func.order]/3 (CWG532)
   25680 
   25681      If only one of the function templates M is a non-static member of some
   25682      class A, M is considered to have a new first parameter inserted in its
   25683      function parameter list. Given cv as the cv-qualifiers of M (if any), the
   25684      new parameter is of type "rvalue reference to cv A" if the optional
   25685      ref-qualifier of M is && or if M has no ref-qualifier and the first
   25686      parameter of the other template has rvalue reference type. Otherwise, the
   25687      new parameter is of type "lvalue reference to cv A".  */
   25688 
   25689   if (DECL_STATIC_FUNCTION_P (decl1) || DECL_STATIC_FUNCTION_P (decl2))
   25690     {
   25691       /* Note C++20 DR2445 extended the above to static member functions, but
   25692 	 I think the old G++ behavior of just skipping the object
   25693 	 parameter when comparing to a static member function was better, so
   25694 	 let's stick with that for now.  This is CWG2834.  --jason 2023-12 */
   25695       if (DECL_OBJECT_MEMBER_FUNCTION_P (decl1))
   25696 	{
   25697 	  len--; /* LEN is the number of significant arguments for DECL1 */
   25698 	  args1 = TREE_CHAIN (args1);
   25699 	}
   25700       else if (DECL_OBJECT_MEMBER_FUNCTION_P (decl2))
   25701 	args2 = TREE_CHAIN (args2);
   25702     }
   25703   else if (DECL_IOBJ_MEMBER_FUNCTION_P (decl1)
   25704 	   && DECL_IOBJ_MEMBER_FUNCTION_P (decl2))
   25705     {
   25706       /* Note DR2445 also (IMO wrongly) removed the "only one" above, which
   25707 	 would break e.g.  cpp1y/lambda-generic-variadic5.C.  */
   25708       len--;
   25709       args1 = TREE_CHAIN (args1);
   25710       args2 = TREE_CHAIN (args2);
   25711     }
   25712   else if (DECL_IOBJ_MEMBER_FUNCTION_P (decl1)
   25713 	   || DECL_IOBJ_MEMBER_FUNCTION_P (decl2))
   25714     {
   25715       /* The other is a non-member or explicit object member function;
   25716 	 rewrite the implicit object parameter to a reference.  */
   25717       tree ns = DECL_IOBJ_MEMBER_FUNCTION_P (decl2) ? decl2 : decl1;
   25718       tree &nsargs = ns == decl2 ? args2 : args1;
   25719       tree obtype = TREE_TYPE (TREE_VALUE (nsargs));
   25720 
   25721       nsargs = TREE_CHAIN (nsargs);
   25722 
   25723       cp_ref_qualifier rqual = type_memfn_rqual (TREE_TYPE (ns));
   25724       if (rqual == REF_QUAL_NONE)
   25725 	{
   25726 	  tree otherfirst = ns == decl1 ? args2 : args1;
   25727 	  otherfirst = TREE_VALUE (otherfirst);
   25728 	  if (TREE_CODE (otherfirst) == REFERENCE_TYPE
   25729 	      && TYPE_REF_IS_RVALUE (otherfirst))
   25730 	    rqual = REF_QUAL_RVALUE;
   25731 	}
   25732       obtype = cp_build_reference_type (obtype, rqual == REF_QUAL_RVALUE);
   25733       nsargs = tree_cons (NULL_TREE, obtype, nsargs);
   25734     }
   25735 
   25736   /* If only one is a conversion operator, they are unordered.  */
   25737   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
   25738     return 0;
   25739 
   25740   /* Consider the return type for a conversion function */
   25741   if (DECL_CONV_FN_P (decl1))
   25742     {
   25743       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
   25744       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
   25745       len++;
   25746     }
   25747 
   25748   processing_template_decl++;
   25749 
   25750   origs1 = args1;
   25751   origs2 = args2;
   25752 
   25753   while (len--
   25754 	 /* Stop when an ellipsis is seen.  */
   25755 	 && args1 != NULL_TREE && args2 != NULL_TREE)
   25756     {
   25757       tree arg1 = TREE_VALUE (args1);
   25758       tree arg2 = TREE_VALUE (args2);
   25759       int deduce1, deduce2;
   25760       int quals1 = -1;
   25761       int quals2 = -1;
   25762       int ref1 = 0;
   25763       int ref2 = 0;
   25764 
   25765       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
   25766           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
   25767         {
   25768           /* When both arguments are pack expansions, we need only
   25769              unify the patterns themselves.  */
   25770           arg1 = PACK_EXPANSION_PATTERN (arg1);
   25771           arg2 = PACK_EXPANSION_PATTERN (arg2);
   25772 
   25773           /* This is the last comparison we need to do.  */
   25774           len = 0;
   25775         }
   25776 
   25777       if (TYPE_REF_P (arg1))
   25778 	{
   25779 	  ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
   25780 	  arg1 = TREE_TYPE (arg1);
   25781 	  quals1 = cp_type_quals (arg1);
   25782 	}
   25783 
   25784       if (TYPE_REF_P (arg2))
   25785 	{
   25786 	  ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
   25787 	  arg2 = TREE_TYPE (arg2);
   25788 	  quals2 = cp_type_quals (arg2);
   25789 	}
   25790 
   25791       arg1 = TYPE_MAIN_VARIANT (arg1);
   25792       arg2 = TYPE_MAIN_VARIANT (arg2);
   25793 
   25794       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
   25795         {
   25796           int i, len2 = remaining_arguments (args2);
   25797           tree parmvec = make_tree_vec (1);
   25798           tree argvec = make_tree_vec (len2);
   25799           tree ta = args2;
   25800 
   25801           /* Setup the parameter vector, which contains only ARG1.  */
   25802           TREE_VEC_ELT (parmvec, 0) = arg1;
   25803 
   25804           /* Setup the argument vector, which contains the remaining
   25805              arguments.  */
   25806           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
   25807             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
   25808 
   25809           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
   25810 					   argvec, DEDUCE_EXACT,
   25811 					   /*subr=*/true, /*explain_p=*/false)
   25812 		     == 0);
   25813 
   25814           /* We cannot deduce in the other direction, because ARG1 is
   25815              a pack expansion but ARG2 is not.  */
   25816           deduce2 = 0;
   25817         }
   25818       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
   25819         {
   25820           int i, len1 = remaining_arguments (args1);
   25821           tree parmvec = make_tree_vec (1);
   25822           tree argvec = make_tree_vec (len1);
   25823           tree ta = args1;
   25824 
   25825           /* Setup the parameter vector, which contains only ARG1.  */
   25826           TREE_VEC_ELT (parmvec, 0) = arg2;
   25827 
   25828           /* Setup the argument vector, which contains the remaining
   25829              arguments.  */
   25830           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
   25831             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
   25832 
   25833           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
   25834 					   argvec, DEDUCE_EXACT,
   25835 					   /*subr=*/true, /*explain_p=*/false)
   25836 		     == 0);
   25837 
   25838           /* We cannot deduce in the other direction, because ARG2 is
   25839              a pack expansion but ARG1 is not.*/
   25840           deduce1 = 0;
   25841         }
   25842 
   25843       else
   25844         {
   25845           /* The normal case, where neither argument is a pack
   25846              expansion.  */
   25847           deduce1 = (unify (tparms1, targs1, arg1, arg2,
   25848 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
   25849 		     == 0);
   25850           deduce2 = (unify (tparms2, targs2, arg2, arg1,
   25851 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
   25852 		     == 0);
   25853         }
   25854 
   25855       /* If we couldn't deduce arguments for tparms1 to make arg1 match
   25856 	 arg2, then arg2 is not as specialized as arg1.  */
   25857       if (!deduce1)
   25858 	lose2 = true;
   25859       if (!deduce2)
   25860 	lose1 = true;
   25861 
   25862       /* "If, for a given type, deduction succeeds in both directions
   25863 	 (i.e., the types are identical after the transformations above)
   25864 	 and both P and A were reference types (before being replaced with
   25865 	 the type referred to above):
   25866 	 - if the type from the argument template was an lvalue reference and
   25867 	 the type from the parameter template was not, the argument type is
   25868 	 considered to be more specialized than the other; otherwise,
   25869 	 - if the type from the argument template is more cv-qualified
   25870 	 than the type from the parameter template (as described above),
   25871 	 the argument type is considered to be more specialized than the other;
   25872 	 otherwise,
   25873 	 - neither type is more specialized than the other."  */
   25874 
   25875       if (deduce1 && deduce2)
   25876 	{
   25877 	  if (ref1 && ref2 && ref1 != ref2)
   25878 	    {
   25879 	      if (ref1 > ref2)
   25880 		lose1 = true;
   25881 	      else
   25882 		lose2 = true;
   25883 	    }
   25884 	  else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
   25885 	    {
   25886 	      if ((quals1 & quals2) == quals2)
   25887 		lose2 = true;
   25888 	      if ((quals1 & quals2) == quals1)
   25889 		lose1 = true;
   25890 	    }
   25891 	}
   25892 
   25893       if (lose1 && lose2)
   25894 	/* We've failed to deduce something in either direction.
   25895 	   These must be unordered.  */
   25896 	break;
   25897 
   25898       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
   25899           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
   25900         /* We have already processed all of the arguments in our
   25901            handing of the pack expansion type.  */
   25902         len = 0;
   25903 
   25904       args1 = TREE_CHAIN (args1);
   25905       args2 = TREE_CHAIN (args2);
   25906     }
   25907 
   25908   /* "In most cases, all template parameters must have values in order for
   25909      deduction to succeed, but for partial ordering purposes a template
   25910      parameter may remain without a value provided it is not used in the
   25911      types being used for partial ordering."
   25912 
   25913      Thus, if we are missing any of the targs1 we need to substitute into
   25914      origs1, then pat2 is not as specialized as pat1.  This can happen when
   25915      there is a nondeduced context.  */
   25916   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
   25917     lose2 = true;
   25918   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
   25919     lose1 = true;
   25920 
   25921   processing_template_decl--;
   25922 
   25923   /* If both deductions succeed, the partial ordering selects the more
   25924      constrained template.  */
   25925   /* P2113: If the corresponding template-parameters of the
   25926      template-parameter-lists are not equivalent ([temp.over.link]) or if
   25927      the function parameters that positionally correspond between the two
   25928      templates are not of the same type, neither template is more
   25929      specialized than the other.  */
   25930   if (!lose1 && !lose2
   25931       && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
   25932 			      DECL_TEMPLATE_PARMS (pat2))
   25933       && compparms (origs1, origs2))
   25934     {
   25935       int winner = more_constrained (decl1, decl2);
   25936       if (winner > 0)
   25937 	lose2 = true;
   25938       else if (winner < 0)
   25939 	lose1 = true;
   25940     }
   25941 
   25942   /* All things being equal, if the next argument is a pack expansion
   25943      for one function but not for the other, prefer the
   25944      non-variadic function.  FIXME this is bogus; see c++/41958.  */
   25945   if (lose1 == lose2
   25946       && args1 && TREE_VALUE (args1)
   25947       && args2 && TREE_VALUE (args2))
   25948     {
   25949       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
   25950       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
   25951     }
   25952 
   25953   if (lose1 == lose2)
   25954     return 0;
   25955   else if (!lose1)
   25956     return 1;
   25957   else
   25958     return -1;
   25959 }
   25960 
   25961 /* Determine which of two partial specializations of TMPL is more
   25962    specialized.
   25963 
   25964    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
   25965    to the first partial specialization.  The TREE_PURPOSE is the
   25966    innermost set of template parameters for the partial
   25967    specialization.  PAT2 is similar, but for the second template.
   25968 
   25969    Return 1 if the first partial specialization is more specialized;
   25970    -1 if the second is more specialized; 0 if neither is more
   25971    specialized.
   25972 
   25973    See [temp.class.order] for information about determining which of
   25974    two templates is more specialized.  */
   25975 
   25976 static int
   25977 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
   25978 {
   25979   tree targs;
   25980   int winner = 0;
   25981   bool any_deductions = false;
   25982 
   25983   tree tmpl1 = TREE_VALUE (pat1);
   25984   tree tmpl2 = TREE_VALUE (pat2);
   25985   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
   25986   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
   25987 
   25988   /* Just like what happens for functions, if we are ordering between
   25989      different template specializations, we may encounter dependent
   25990      types in the arguments, and we need our dependency check functions
   25991      to behave correctly.  */
   25992   ++processing_template_decl;
   25993   targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
   25994   if (targs)
   25995     {
   25996       --winner;
   25997       any_deductions = true;
   25998     }
   25999 
   26000   targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
   26001   if (targs)
   26002     {
   26003       ++winner;
   26004       any_deductions = true;
   26005     }
   26006   --processing_template_decl;
   26007 
   26008   /* If both deductions succeed, the partial ordering selects the more
   26009      constrained template.  */
   26010   if (!winner && any_deductions)
   26011     winner = more_constrained (tmpl1, tmpl2);
   26012 
   26013   /* In the case of a tie where at least one of the templates
   26014      has a parameter pack at the end, the template with the most
   26015      non-packed parameters wins.  */
   26016   if (winner == 0
   26017       && any_deductions
   26018       && (template_args_variadic_p (TREE_PURPOSE (pat1))
   26019           || template_args_variadic_p (TREE_PURPOSE (pat2))))
   26020     {
   26021       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
   26022       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
   26023       int len1 = TREE_VEC_LENGTH (args1);
   26024       int len2 = TREE_VEC_LENGTH (args2);
   26025 
   26026       /* We don't count the pack expansion at the end.  */
   26027       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
   26028         --len1;
   26029       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
   26030         --len2;
   26031 
   26032       if (len1 > len2)
   26033         return 1;
   26034       else if (len1 < len2)
   26035         return -1;
   26036     }
   26037 
   26038   return winner;
   26039 }
   26040 
   26041 /* Return the template arguments that will produce the function signature
   26042    DECL from the function template FN, with the explicit template
   26043    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
   26044    also match.  Return NULL_TREE if no satisfactory arguments could be
   26045    found.  */
   26046 
   26047 static tree
   26048 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
   26049 {
   26050   int ntparms = DECL_NTPARMS (fn);
   26051   tree targs = make_tree_vec (ntparms);
   26052   tree decl_type = TREE_TYPE (decl);
   26053   tree decl_arg_types;
   26054   tree *args;
   26055   unsigned int nargs, ix;
   26056   tree arg;
   26057 
   26058   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
   26059 
   26060   /* Never do unification on the 'this' parameter.  */
   26061   decl_arg_types = skip_artificial_parms_for (decl,
   26062 					      TYPE_ARG_TYPES (decl_type));
   26063 
   26064   nargs = list_length (decl_arg_types);
   26065   args = XALLOCAVEC (tree, nargs);
   26066   for (arg = decl_arg_types, ix = 0;
   26067        arg != NULL_TREE;
   26068        arg = TREE_CHAIN (arg), ++ix)
   26069     args[ix] = TREE_VALUE (arg);
   26070 
   26071   if (fn_type_unification (fn, explicit_args, targs,
   26072 			   args, ix,
   26073 			   (check_rettype || DECL_CONV_FN_P (fn)
   26074 			    ? TREE_TYPE (decl_type) : NULL_TREE),
   26075 			   DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
   26076 			   /*explain_p=*/false,
   26077 			   /*decltype*/false)
   26078       == error_mark_node)
   26079     return NULL_TREE;
   26080 
   26081   return targs;
   26082 }
   26083 
   26084 /* Return the innermost template arguments that, when applied to a partial
   26085    specialization SPEC_TMPL of TMPL, yield the ARGS.
   26086 
   26087    For example, suppose we have:
   26088 
   26089      template <class T, class U> struct S {};
   26090      template <class T> struct S<T*, int> {};
   26091 
   26092    Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
   26093    partial specialization and the ARGS will be {double*, int}.  The resulting
   26094    vector will be {double}, indicating that `T' is bound to `double'.  */
   26095 
   26096 static tree
   26097 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
   26098 {
   26099   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
   26100   tree spec_args
   26101     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
   26102   int i, ntparms = TREE_VEC_LENGTH (tparms);
   26103   tree deduced_args;
   26104   tree innermost_deduced_args;
   26105 
   26106   innermost_deduced_args = make_tree_vec (ntparms);
   26107   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
   26108     {
   26109       deduced_args = copy_node (args);
   26110       SET_TMPL_ARGS_LEVEL (deduced_args,
   26111 			   TMPL_ARGS_DEPTH (deduced_args),
   26112 			   innermost_deduced_args);
   26113     }
   26114   else
   26115     deduced_args = innermost_deduced_args;
   26116 
   26117   bool tried_array_deduction = (cxx_dialect < cxx17);
   26118  again:
   26119   if (unify (tparms, deduced_args,
   26120 	     INNERMOST_TEMPLATE_ARGS (spec_args),
   26121 	     INNERMOST_TEMPLATE_ARGS (args),
   26122 	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
   26123     return NULL_TREE;
   26124 
   26125   for (i =  0; i < ntparms; ++i)
   26126     if (! TREE_VEC_ELT (innermost_deduced_args, i))
   26127       {
   26128 	if (!tried_array_deduction)
   26129 	  {
   26130 	    try_array_deduction (tparms, innermost_deduced_args,
   26131 				 INNERMOST_TEMPLATE_ARGS (spec_args));
   26132 	    tried_array_deduction = true;
   26133 	    if (TREE_VEC_ELT (innermost_deduced_args, i))
   26134 	      goto again;
   26135 	  }
   26136 	return NULL_TREE;
   26137       }
   26138 
   26139   if (!push_tinst_level (spec_tmpl, deduced_args))
   26140     {
   26141       excessive_deduction_depth = true;
   26142       return NULL_TREE;
   26143     }
   26144 
   26145   /* Verify that nondeduced template arguments agree with the type
   26146      obtained from argument deduction.
   26147 
   26148      For example:
   26149 
   26150        struct A { typedef int X; };
   26151        template <class T, class U> struct C {};
   26152        template <class T> struct C<T, typename T::X> {};
   26153 
   26154      Then with the instantiation `C<A, int>', we can deduce that
   26155      `T' is `A' but unify () does not check whether `typename T::X'
   26156      is `int'.  */
   26157   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
   26158 
   26159   if (spec_args != error_mark_node)
   26160     spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
   26161 				       INNERMOST_TEMPLATE_ARGS (spec_args),
   26162 				       tmpl, tf_none, false);
   26163 
   26164   pop_tinst_level ();
   26165 
   26166   if (spec_args == error_mark_node
   26167       /* We only need to check the innermost arguments; the other
   26168 	 arguments will always agree.  */
   26169       || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
   26170 				     INNERMOST_TEMPLATE_ARGS (args)))
   26171     return NULL_TREE;
   26172 
   26173   /* Now that we have bindings for all of the template arguments,
   26174      ensure that the arguments deduced for the template template
   26175      parameters have compatible template parameter lists.  See the use
   26176      of template_template_parm_bindings_ok_p in fn_type_unification
   26177      for more information.  */
   26178   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
   26179     return NULL_TREE;
   26180 
   26181   return deduced_args;
   26182 }
   26183 
   26184 // Compare two function templates T1 and T2 by deducing bindings
   26185 // from one against the other. If both deductions succeed, compare
   26186 // constraints to see which is more constrained.
   26187 static int
   26188 more_specialized_inst (tree t1, tree t2)
   26189 {
   26190   int fate = 0;
   26191   int count = 0;
   26192 
   26193   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
   26194     {
   26195       --fate;
   26196       ++count;
   26197     }
   26198 
   26199   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
   26200     {
   26201       ++fate;
   26202       ++count;
   26203     }
   26204 
   26205   // If both deductions succeed, then one may be more constrained.
   26206   if (count == 2 && fate == 0)
   26207     fate = more_constrained (t1, t2);
   26208 
   26209   return fate;
   26210 }
   26211 
   26212 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
   26213    Return the TREE_LIST node with the most specialized template, if
   26214    any.  If there is no most specialized template, the error_mark_node
   26215    is returned.
   26216 
   26217    Note that this function does not look at, or modify, the
   26218    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
   26219    returned is one of the elements of INSTANTIATIONS, callers may
   26220    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
   26221    and retrieve it from the value returned.  */
   26222 
   26223 tree
   26224 most_specialized_instantiation (tree templates)
   26225 {
   26226   tree fn, champ;
   26227 
   26228   ++processing_template_decl;
   26229 
   26230   champ = templates;
   26231   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
   26232     {
   26233       gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
   26234       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
   26235       if (fate == -1)
   26236 	champ = fn;
   26237       else if (!fate)
   26238 	{
   26239 	  /* Equally specialized, move to next function.  If there
   26240 	     is no next function, nothing's most specialized.  */
   26241 	  fn = TREE_CHAIN (fn);
   26242 	  champ = fn;
   26243 	  if (!fn)
   26244 	    break;
   26245 	}
   26246     }
   26247 
   26248   if (champ)
   26249     /* Now verify that champ is better than everything earlier in the
   26250        instantiation list.  */
   26251     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
   26252       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
   26253       {
   26254         champ = NULL_TREE;
   26255         break;
   26256       }
   26257     }
   26258 
   26259   processing_template_decl--;
   26260 
   26261   if (!champ)
   26262     return error_mark_node;
   26263 
   26264   return champ;
   26265 }
   26266 
   26267 /* If DECL is a specialization of some template, return the most
   26268    general such template.  Otherwise, returns NULL_TREE.
   26269 
   26270    For example, given:
   26271 
   26272      template <class T> struct S { template <class U> void f(U); };
   26273 
   26274    if TMPL is `template <class U> void S<int>::f(U)' this will return
   26275    the full template.  This function will not trace past partial
   26276    specializations, however.  For example, given in addition:
   26277 
   26278      template <class T> struct S<T*> { template <class U> void f(U); };
   26279 
   26280    if TMPL is `template <class U> void S<int*>::f(U)' this will return
   26281    `template <class T> template <class U> S<T*>::f(U)'.  */
   26282 
   26283 tree
   26284 most_general_template (const_tree decl)
   26285 {
   26286   if (TREE_CODE (decl) != TEMPLATE_DECL)
   26287     {
   26288       if (tree tinfo = get_template_info (decl))
   26289 	decl = TI_TEMPLATE (tinfo);
   26290       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
   26291 	 template friend, or a FIELD_DECL for a capture pack.  */
   26292       if (TREE_CODE (decl) != TEMPLATE_DECL)
   26293 	return NULL_TREE;
   26294     }
   26295 
   26296   if (DECL_TEMPLATE_TEMPLATE_PARM_P (decl))
   26297     return DECL_TI_TEMPLATE (DECL_TEMPLATE_RESULT (decl));
   26298 
   26299   /* Look for more and more general templates.  */
   26300   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
   26301     {
   26302       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
   26303 	 (See cp-tree.h for details.)  */
   26304       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
   26305 	break;
   26306 
   26307       if (CLASS_TYPE_P (TREE_TYPE (decl))
   26308 	  && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
   26309 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
   26310 	break;
   26311 
   26312       /* Stop if we run into an explicitly specialized class template.  */
   26313       if (!DECL_NAMESPACE_SCOPE_P (decl)
   26314 	  && DECL_CONTEXT (decl)
   26315 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
   26316 	break;
   26317 
   26318       decl = DECL_TI_TEMPLATE (decl);
   26319     }
   26320 
   26321   return CONST_CAST_TREE (decl);
   26322 }
   26323 
   26324 /* Return the most specialized of the template partial specializations
   26325    which can produce TARGET, a specialization of some class or variable
   26326    template.  The value returned is a TEMPLATE_INFO; the TI_TEMPLATE is a
   26327    TEMPLATE_DECL node corresponding to the partial specialization, while
   26328    the TI_ARGS is the set of template arguments that must be substituted
   26329    into the template pattern in order to generate TARGET.  The result is
   26330    cached in the TI_PARTIAL_INFO of the corresponding TEMPLATE_INFO unless
   26331    RECHECKING is true.
   26332 
   26333    If the choice of partial specialization is ambiguous, a diagnostic
   26334    is issued, and the error_mark_node is returned.  If there are no
   26335    partial specializations matching TARGET, then NULL_TREE is
   26336    returned, indicating that the primary template should be used.  */
   26337 
   26338 tree
   26339 most_specialized_partial_spec (tree target, tsubst_flags_t complain,
   26340 			       bool rechecking /* = false */)
   26341 {
   26342   tree tinfo = NULL_TREE;
   26343   tree tmpl, args, decl;
   26344   if (TYPE_P (target))
   26345     {
   26346       tinfo = CLASSTYPE_TEMPLATE_INFO (target);
   26347       tmpl = TI_TEMPLATE (tinfo);
   26348       args = TI_ARGS (tinfo);
   26349       decl = TYPE_NAME (target);
   26350     }
   26351   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
   26352     {
   26353       tmpl = TREE_OPERAND (target, 0);
   26354       args = TREE_OPERAND (target, 1);
   26355       decl = DECL_TEMPLATE_RESULT (tmpl);
   26356     }
   26357   else if (VAR_P (target))
   26358     {
   26359       tinfo = DECL_TEMPLATE_INFO (target);
   26360       tmpl = TI_TEMPLATE (tinfo);
   26361       args = TI_ARGS (tinfo);
   26362       decl = target;
   26363     }
   26364   else
   26365     gcc_unreachable ();
   26366 
   26367   if (!PRIMARY_TEMPLATE_P (tmpl))
   26368     return NULL_TREE;
   26369 
   26370   if (!rechecking
   26371       && tinfo
   26372       && (VAR_P (target) || COMPLETE_TYPE_P (target)))
   26373     return TI_PARTIAL_INFO (tinfo);
   26374 
   26375   tree main_tmpl = most_general_template (tmpl);
   26376   tree specs = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl);
   26377   if (!specs)
   26378     /* There are no partial specializations of this template.  */
   26379     return NULL_TREE;
   26380 
   26381   push_access_scope_guard pas (decl);
   26382   deferring_access_check_sentinel acs (dk_no_deferred);
   26383 
   26384   /* For determining which partial specialization to use, only the
   26385      innermost args are interesting.  */
   26386   tree outer_args = NULL_TREE;
   26387   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
   26388     {
   26389       outer_args = strip_innermost_template_args (args, 1);
   26390       args = INNERMOST_TEMPLATE_ARGS (args);
   26391     }
   26392 
   26393   /* The caller hasn't called push_to_top_level yet, but we need
   26394      get_partial_spec_bindings to be done in non-template context so that we'll
   26395      fully resolve everything.  */
   26396   processing_template_decl_sentinel ptds;
   26397 
   26398   tree list = NULL_TREE;
   26399   for (tree t = specs; t; t = TREE_CHAIN (t))
   26400     {
   26401       const tree ospec_tmpl = TREE_VALUE (t);
   26402 
   26403       tree spec_tmpl;
   26404       if (outer_args)
   26405 	{
   26406 	  /* Substitute in the template args from the enclosing class.  */
   26407 	  ++processing_template_decl;
   26408 	  spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
   26409 	  --processing_template_decl;
   26410 	  if (spec_tmpl == error_mark_node)
   26411 	    return error_mark_node;
   26412 	}
   26413       else
   26414 	spec_tmpl = ospec_tmpl;
   26415 
   26416       tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
   26417       if (spec_args)
   26418 	{
   26419 	  if (outer_args)
   26420 	    spec_args = add_to_template_args (outer_args, spec_args);
   26421 
   26422 	  /* Keep the candidate only if its constraints are satisfied.  */
   26423 	  if (constraints_satisfied_p (ospec_tmpl, spec_args))
   26424 	    list = tree_cons (spec_args, ospec_tmpl, list);
   26425 	}
   26426     }
   26427 
   26428   if (! list)
   26429     return NULL_TREE;
   26430 
   26431   tree champ = list;
   26432   bool ambiguous_p = false;
   26433   for (tree t = TREE_CHAIN (list); t; t = TREE_CHAIN (t))
   26434     {
   26435       int fate = more_specialized_partial_spec (tmpl, champ, t);
   26436       if (fate == 1)
   26437 	;
   26438       else
   26439 	{
   26440 	  if (fate == 0)
   26441 	    {
   26442 	      t = TREE_CHAIN (t);
   26443 	      if (! t)
   26444 		{
   26445 		  ambiguous_p = true;
   26446 		  break;
   26447 		}
   26448 	    }
   26449 	  champ = t;
   26450 	}
   26451     }
   26452 
   26453   if (!ambiguous_p)
   26454     for (tree t = list; t && t != champ; t = TREE_CHAIN (t))
   26455       {
   26456 	int fate = more_specialized_partial_spec (tmpl, champ, t);
   26457 	if (fate != 1)
   26458 	  {
   26459 	    ambiguous_p = true;
   26460 	    break;
   26461 	  }
   26462       }
   26463 
   26464   if (ambiguous_p)
   26465     {
   26466       const char *str;
   26467       char *spaces = NULL;
   26468       if (!(complain & tf_error))
   26469 	return error_mark_node;
   26470       if (TYPE_P (target))
   26471 	error ("ambiguous template instantiation for %q#T", target);
   26472       else
   26473 	error ("ambiguous template instantiation for %q#D", target);
   26474       str = ngettext ("candidate is:", "candidates are:", list_length (list));
   26475       for (tree t = list; t; t = TREE_CHAIN (t))
   26476         {
   26477 	  tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
   26478           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
   26479 		  "%s %#qS", spaces ? spaces : str, subst);
   26480           spaces = spaces ? spaces : get_spaces (str);
   26481         }
   26482       free (spaces);
   26483       return error_mark_node;
   26484     }
   26485 
   26486   tree result = build_template_info (TREE_VALUE (champ), TREE_PURPOSE (champ));
   26487   if (!rechecking && tinfo)
   26488     TI_PARTIAL_INFO (tinfo) = result;
   26489   return result;
   26490 }
   26491 
   26492 /* Explicitly instantiate DECL.  */
   26493 
   26494 void
   26495 do_decl_instantiation (tree decl, tree storage)
   26496 {
   26497   tree result = NULL_TREE;
   26498   int extern_p = 0;
   26499 
   26500   if (!decl || decl == error_mark_node)
   26501     /* An error occurred, for which grokdeclarator has already issued
   26502        an appropriate message.  */
   26503     return;
   26504   else if (! DECL_LANG_SPECIFIC (decl))
   26505     {
   26506       error ("explicit instantiation of non-template %q#D", decl);
   26507       return;
   26508     }
   26509   else if (DECL_DECLARED_CONCEPT_P (decl))
   26510     {
   26511       if (VAR_P (decl))
   26512 	error ("explicit instantiation of variable concept %q#D", decl);
   26513       else
   26514 	error ("explicit instantiation of function concept %q#D", decl);
   26515       return;
   26516     }
   26517 
   26518   bool var_templ = (DECL_TEMPLATE_INFO (decl)
   26519                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
   26520 
   26521   if (VAR_P (decl) && !var_templ)
   26522     {
   26523       /* There is an asymmetry here in the way VAR_DECLs and
   26524 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
   26525 	 the latter, the DECL we get back will be marked as a
   26526 	 template instantiation, and the appropriate
   26527 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
   26528 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
   26529 	 should handle VAR_DECLs as it currently handles
   26530 	 FUNCTION_DECLs.  */
   26531       if (!DECL_CLASS_SCOPE_P (decl))
   26532 	{
   26533 	  error ("%qD is not a static data member of a class template", decl);
   26534 	  return;
   26535 	}
   26536       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
   26537       if (!result || !VAR_P (result))
   26538 	{
   26539 	  error ("no matching template for %qD found", decl);
   26540 	  return;
   26541 	}
   26542       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
   26543 	{
   26544 	  error ("type %qT for explicit instantiation %qD does not match "
   26545 		 "declared type %qT", TREE_TYPE (result), decl,
   26546 		 TREE_TYPE (decl));
   26547 	  return;
   26548 	}
   26549     }
   26550   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
   26551     {
   26552       error ("explicit instantiation of %q#D", decl);
   26553       return;
   26554     }
   26555   else
   26556     result = decl;
   26557 
   26558   /* Check for various error cases.  Note that if the explicit
   26559      instantiation is valid the RESULT will currently be marked as an
   26560      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
   26561      until we get here.  */
   26562 
   26563   if (DECL_TEMPLATE_SPECIALIZATION (result))
   26564     {
   26565       /* DR 259 [temp.spec].
   26566 
   26567 	 Both an explicit instantiation and a declaration of an explicit
   26568 	 specialization shall not appear in a program unless the explicit
   26569 	 instantiation follows a declaration of the explicit specialization.
   26570 
   26571 	 For a given set of template parameters, if an explicit
   26572 	 instantiation of a template appears after a declaration of an
   26573 	 explicit specialization for that template, the explicit
   26574 	 instantiation has no effect.  */
   26575       return;
   26576     }
   26577   else if (DECL_EXPLICIT_INSTANTIATION (result))
   26578     {
   26579       /* [temp.spec]
   26580 
   26581 	 No program shall explicitly instantiate any template more
   26582 	 than once.
   26583 
   26584 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
   26585 	 the first instantiation was `extern' and the second is not,
   26586 	 and EXTERN_P for the opposite case.  */
   26587       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
   26588 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
   26589       /* If an "extern" explicit instantiation follows an ordinary
   26590 	 explicit instantiation, the template is instantiated.  */
   26591       if (extern_p)
   26592 	return;
   26593     }
   26594   else if (!DECL_IMPLICIT_INSTANTIATION (result))
   26595     {
   26596       error ("no matching template for %qD found", result);
   26597       return;
   26598     }
   26599   else if (!DECL_TEMPLATE_INFO (result))
   26600     {
   26601       permerror (input_location, "explicit instantiation of non-template %q#D", result);
   26602       return;
   26603     }
   26604 
   26605   if (storage == NULL_TREE)
   26606     ;
   26607   else if (storage == ridpointers[(int) RID_EXTERN])
   26608     {
   26609       if (cxx_dialect == cxx98)
   26610 	pedwarn (input_location, OPT_Wpedantic,
   26611 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
   26612 		 "instantiations");
   26613       extern_p = 1;
   26614     }
   26615   else
   26616     error ("storage class %qD applied to template instantiation", storage);
   26617 
   26618   check_explicit_instantiation_namespace (result);
   26619   mark_decl_instantiated (result, extern_p);
   26620   if (! extern_p)
   26621     instantiate_decl (result, /*defer_ok=*/true,
   26622 		      /*expl_inst_class_mem_p=*/false);
   26623 }
   26624 
   26625 static void
   26626 mark_class_instantiated (tree t, int extern_p)
   26627 {
   26628   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
   26629   SET_CLASSTYPE_INTERFACE_KNOWN (t);
   26630   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
   26631   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
   26632   if (! extern_p)
   26633     {
   26634       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
   26635       rest_of_type_compilation (t, 1);
   26636     }
   26637 }
   26638 
   26639 /* Perform an explicit instantiation of template class T.  STORAGE, if
   26640    non-null, is the RID for extern, inline or static.  COMPLAIN is
   26641    nonzero if this is called from the parser, zero if called recursively,
   26642    since the standard is unclear (as detailed below).  */
   26643 
   26644 void
   26645 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
   26646 {
   26647   if (!(CLASS_TYPE_P (t) && CLASSTYPE_TEMPLATE_INFO (t)))
   26648     {
   26649       if (tree ti = TYPE_TEMPLATE_INFO (t))
   26650 	error ("explicit instantiation of non-class template %qD",
   26651 	       TI_TEMPLATE (ti));
   26652       else
   26653 	error ("explicit instantiation of non-template type %qT", t);
   26654       return;
   26655     }
   26656 
   26657   complete_type (t);
   26658 
   26659   if (!COMPLETE_TYPE_P (t))
   26660     {
   26661       if (complain & tf_error)
   26662 	error ("explicit instantiation of %q#T before definition of template",
   26663 	       t);
   26664       return;
   26665     }
   26666 
   26667   /* At most one of these will be true.  */
   26668   bool extern_p = false;
   26669   bool nomem_p = false;
   26670   bool static_p = false;
   26671 
   26672   if (storage != NULL_TREE)
   26673     {
   26674       if (storage == ridpointers[(int) RID_EXTERN])
   26675 	{
   26676 	  if (cxx_dialect == cxx98)
   26677 	    pedwarn (input_location, OPT_Wpedantic,
   26678 		     "ISO C++ 1998 forbids the use of %<extern%> on "
   26679 		     "explicit instantiations");
   26680 	}
   26681       else
   26682 	pedwarn (input_location, OPT_Wpedantic,
   26683 		 "ISO C++ forbids the use of %qE"
   26684 		 " on explicit instantiations", storage);
   26685 
   26686       if (storage == ridpointers[(int) RID_INLINE])
   26687 	nomem_p = true;
   26688       else if (storage == ridpointers[(int) RID_EXTERN])
   26689 	extern_p = true;
   26690       else if (storage == ridpointers[(int) RID_STATIC])
   26691 	static_p = true;
   26692       else
   26693 	error ("storage class %qD applied to template instantiation",
   26694 	       storage);
   26695     }
   26696 
   26697   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
   26698     /* DR 259 [temp.spec].
   26699 
   26700        Both an explicit instantiation and a declaration of an explicit
   26701        specialization shall not appear in a program unless the
   26702        explicit instantiation follows a declaration of the explicit
   26703        specialization.
   26704 
   26705        For a given set of template parameters, if an explicit
   26706        instantiation of a template appears after a declaration of an
   26707        explicit specialization for that template, the explicit
   26708        instantiation has no effect.  */
   26709     return;
   26710 
   26711   if (CLASSTYPE_EXPLICIT_INSTANTIATION (t) && !CLASSTYPE_INTERFACE_ONLY (t))
   26712     {
   26713       /* We've already instantiated the template.  */
   26714 
   26715       /* [temp.spec]
   26716 
   26717 	 No program shall explicitly instantiate any template more
   26718 	 than once.
   26719 
   26720 	 If EXTERN_P then this is ok.  */
   26721       if (!extern_p && (complain & tf_error))
   26722 	permerror (input_location,
   26723 		   "duplicate explicit instantiation of %q#T", t);
   26724 
   26725       return;
   26726     }
   26727 
   26728   check_explicit_instantiation_namespace (TYPE_NAME (t));
   26729   mark_class_instantiated (t, extern_p);
   26730 
   26731   if (nomem_p)
   26732     return;
   26733 
   26734   /* In contrast to implicit instantiation, where only the
   26735      declarations, and not the definitions, of members are
   26736      instantiated, we have here:
   26737 
   26738 	 [temp.explicit]
   26739 
   26740 	 An explicit instantiation that names a class template
   26741 	 specialization is also an explicit instantiation of the same
   26742 	 kind (declaration or definition) of each of its members (not
   26743 	 including members inherited from base classes and members
   26744 	 that are templates) that has not been previously explicitly
   26745 	 specialized in the translation unit containing the explicit
   26746 	 instantiation, provided that the associated constraints, if
   26747 	 any, of that member are satisfied by the template arguments
   26748 	 of the explicit instantiation.  */
   26749   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
   26750     if ((VAR_P (fld)
   26751 	 || (TREE_CODE (fld) == FUNCTION_DECL
   26752 	     && !static_p
   26753 	     && user_provided_p (fld)))
   26754 	&& DECL_TEMPLATE_INSTANTIATION (fld)
   26755 	&& constraints_satisfied_p (fld))
   26756       {
   26757 	mark_decl_instantiated (fld, extern_p);
   26758 	if (! extern_p)
   26759 	  instantiate_decl (fld, /*defer_ok=*/true,
   26760 			    /*expl_inst_class_mem_p=*/true);
   26761       }
   26762     else if (DECL_IMPLICIT_TYPEDEF_P (fld))
   26763       {
   26764 	tree type = TREE_TYPE (fld);
   26765 
   26766 	if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
   26767 	    && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
   26768 	  do_type_instantiation (type, storage, 0);
   26769       }
   26770 }
   26771 
   26772 /* Given a function DECL, which is a specialization of TMPL, modify
   26773    DECL to be a re-instantiation of TMPL with the same template
   26774    arguments.  TMPL should be the template into which tsubst'ing
   26775    should occur for DECL, not the most general template.
   26776 
   26777    One reason for doing this is a scenario like this:
   26778 
   26779      template <class T>
   26780      void f(const T&, int i);
   26781 
   26782      void g() { f(3, 7); }
   26783 
   26784      template <class T>
   26785      void f(const T& t, const int i) { }
   26786 
   26787    Note that when the template is first instantiated, with
   26788    instantiate_template, the resulting DECL will have no name for the
   26789    first parameter, and the wrong type for the second.  So, when we go
   26790    to instantiate the DECL, we regenerate it.  */
   26791 
   26792 static void
   26793 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
   26794 {
   26795   /* The arguments used to instantiate DECL, from the most general
   26796      template.  */
   26797   tree code_pattern = DECL_TEMPLATE_RESULT (tmpl);
   26798 
   26799   /* Make sure that we can see identifiers, and compute access correctly.  */
   26800   push_access_scope (decl);
   26801 
   26802   if (TREE_CODE (decl) == FUNCTION_DECL)
   26803     {
   26804       tree specs;
   26805       int args_depth;
   26806       int parms_depth;
   26807 
   26808       /* Don't bother with this for unique friends that can't be redeclared and
   26809 	 might change type if regenerated (PR69836).  */
   26810       if (DECL_UNIQUE_FRIEND_P (decl))
   26811 	goto done;
   26812 
   26813       /* Use the source location of the definition.  */
   26814       DECL_SOURCE_LOCATION (decl) = DECL_SOURCE_LOCATION (tmpl);
   26815 
   26816       args_depth = TMPL_ARGS_DEPTH (args);
   26817       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
   26818       if (args_depth > parms_depth)
   26819 	args = get_innermost_template_args (args, parms_depth);
   26820 
   26821       /* Instantiate a dynamic exception-specification.  noexcept will be
   26822 	 handled below.  */
   26823       if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
   26824 	if (TREE_VALUE (raises))
   26825 	  {
   26826 	    specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
   26827 						    args, tf_error, NULL_TREE,
   26828 						    /*defer_ok*/false);
   26829 	    if (specs && specs != error_mark_node)
   26830 	      TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
   26831 							  specs);
   26832 	  }
   26833 
   26834       /* Merge parameter declarations.  */
   26835       if (tree pattern_parm
   26836 	  = skip_artificial_parms_for (code_pattern,
   26837 				       DECL_ARGUMENTS (code_pattern)))
   26838 	{
   26839 	  tree *p = &DECL_ARGUMENTS (decl);
   26840 	  for (int skip = num_artificial_parms_for (decl); skip; --skip)
   26841 	    p = &DECL_CHAIN (*p);
   26842 	  *p = tsubst_decl (pattern_parm, args, tf_error);
   26843 	  for (tree t = *p; t; t = DECL_CHAIN (t))
   26844 	    DECL_CONTEXT (t) = decl;
   26845 	}
   26846 
   26847       if (DECL_CONTRACTS (decl))
   26848 	{
   26849 	  /* If we're regenerating a specialization, the contracts will have
   26850 	     been copied from the most general template. Replace those with
   26851 	     the ones from the actual specialization.  */
   26852 	  tree tmpl = DECL_TI_TEMPLATE (decl);
   26853 	  if (DECL_TEMPLATE_SPECIALIZATION (tmpl))
   26854 	    {
   26855 	      remove_contract_attributes (decl);
   26856 	      copy_contract_attributes (decl, code_pattern);
   26857 	    }
   26858 
   26859 	  tsubst_contract_attributes (decl, args, tf_warning_or_error, code_pattern);
   26860 	}
   26861 
   26862       /* Merge additional specifiers from the CODE_PATTERN.  */
   26863       if (DECL_DECLARED_INLINE_P (code_pattern)
   26864 	  && !DECL_DECLARED_INLINE_P (decl))
   26865 	DECL_DECLARED_INLINE_P (decl) = 1;
   26866 
   26867       maybe_instantiate_noexcept (decl, tf_error);
   26868     }
   26869   else if (VAR_P (decl))
   26870     {
   26871       start_lambda_scope (decl);
   26872       DECL_INITIAL (decl) =
   26873 	tsubst_init (DECL_INITIAL (code_pattern), decl, args,
   26874 		     tf_error, DECL_TI_TEMPLATE (decl));
   26875       finish_lambda_scope ();
   26876       if (VAR_HAD_UNKNOWN_BOUND (decl))
   26877 	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
   26878 				   tf_error, DECL_TI_TEMPLATE (decl));
   26879     }
   26880   else
   26881     gcc_unreachable ();
   26882 
   26883  done:
   26884   pop_access_scope (decl);
   26885 }
   26886 
   26887 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
   26888    substituted to get DECL.  */
   26889 
   26890 tree
   26891 template_for_substitution (tree decl)
   26892 {
   26893   tree tmpl = DECL_TI_TEMPLATE (decl);
   26894 
   26895   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
   26896      for the instantiation.  This is not always the most general
   26897      template.  Consider, for example:
   26898 
   26899 	template <class T>
   26900 	struct S { template <class U> void f();
   26901 		   template <> void f<int>(); };
   26902 
   26903      and an instantiation of S<double>::f<int>.  We want TD to be the
   26904      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
   26905   while (/* An instantiation cannot have a definition, so we need a
   26906 	    more general template.  */
   26907 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
   26908 	   /* We must also deal with friend templates.  Given:
   26909 
   26910 		template <class T> struct S {
   26911 		  template <class U> friend void f() {};
   26912 		};
   26913 
   26914 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
   26915 	      so far as the language is concerned, but that's still
   26916 	      where we get the pattern for the instantiation from.  On
   26917 	      other hand, if the definition comes outside the class, say:
   26918 
   26919 		template <class T> struct S {
   26920 		  template <class U> friend void f();
   26921 		};
   26922 		template <class U> friend void f() {}
   26923 
   26924 	      we don't need to look any further.  That's what the check for
   26925 	      DECL_INITIAL is for.  */
   26926 	  || (TREE_CODE (decl) == FUNCTION_DECL
   26927 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
   26928 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
   26929     {
   26930       /* The present template, TD, should not be a definition.  If it
   26931 	 were a definition, we should be using it!  Note that we
   26932 	 cannot restructure the loop to just keep going until we find
   26933 	 a template with a definition, since that might go too far if
   26934 	 a specialization was declared, but not defined.  */
   26935 
   26936       /* Fetch the more general template.  */
   26937       tmpl = DECL_TI_TEMPLATE (tmpl);
   26938     }
   26939 
   26940   return tmpl;
   26941 }
   26942 
   26943 /* Returns true if we need to instantiate this template instance even if we
   26944    know we aren't going to emit it.  */
   26945 
   26946 bool
   26947 always_instantiate_p (tree decl)
   26948 {
   26949   /* We always instantiate inline functions so that we can inline them.  An
   26950      explicit instantiation declaration prohibits implicit instantiation of
   26951      non-inline functions.  With high levels of optimization, we would
   26952      normally inline non-inline functions -- but we're not allowed to do
   26953      that for "extern template" functions.  Therefore, we check
   26954      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
   26955   return ((TREE_CODE (decl) == FUNCTION_DECL
   26956 	   && (DECL_DECLARED_INLINE_P (decl)
   26957 	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
   26958 	  /* And we need to instantiate static data members so that
   26959 	     their initializers are available in integral constant
   26960 	     expressions.  */
   26961 	  || (VAR_P (decl)
   26962 	      && decl_maybe_constant_var_p (decl)));
   26963 }
   26964 
   26965 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
   26966    instantiate it now, modifying TREE_TYPE (fn).  Returns false on
   26967    error, true otherwise.  */
   26968 
   26969 bool
   26970 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
   26971 {
   26972   if (fn == error_mark_node)
   26973     return false;
   26974 
   26975   /* Don't instantiate a noexcept-specification from template context.  */
   26976   if (processing_template_decl
   26977       && (!flag_noexcept_type || type_dependent_expression_p (fn)))
   26978     return true;
   26979 
   26980   tree fntype = TREE_TYPE (fn);
   26981   tree spec = TYPE_RAISES_EXCEPTIONS (fntype);
   26982 
   26983   if ((!spec || UNEVALUATED_NOEXCEPT_SPEC_P (spec))
   26984       && DECL_MAYBE_DELETED (fn))
   26985     {
   26986       if (fn == current_function_decl)
   26987 	/* We're in start_preparsed_function, keep going.  */
   26988 	return true;
   26989 
   26990       ++function_depth;
   26991       maybe_synthesize_method (fn);
   26992       --function_depth;
   26993       return !DECL_DELETED_FN (fn);
   26994     }
   26995 
   26996   if (!spec || !TREE_PURPOSE (spec))
   26997     return true;
   26998 
   26999   tree noex = TREE_PURPOSE (spec);
   27000   if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
   27001       && TREE_CODE (noex) != DEFERRED_PARSE)
   27002     return true;
   27003 
   27004   tree orig_fn = NULL_TREE;
   27005   /* For a member friend template we can get a TEMPLATE_DECL.  Let's use
   27006      its FUNCTION_DECL for the rest of this function -- push_access_scope
   27007      doesn't accept TEMPLATE_DECLs.  */
   27008   if (DECL_FUNCTION_TEMPLATE_P (fn))
   27009     {
   27010       orig_fn = fn;
   27011       fn = DECL_TEMPLATE_RESULT (fn);
   27012     }
   27013 
   27014   if (DECL_CLONED_FUNCTION_P (fn))
   27015     {
   27016       tree prime = DECL_CLONED_FUNCTION (fn);
   27017       if (!maybe_instantiate_noexcept (prime, complain))
   27018 	return false;
   27019       spec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (prime));
   27020     }
   27021   else if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
   27022     {
   27023       static hash_set<tree>* fns = new hash_set<tree>;
   27024       bool added = false;
   27025       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
   27026 	{
   27027 	  spec = get_defaulted_eh_spec (fn, complain);
   27028 	  if (spec == error_mark_node)
   27029 	    /* This might have failed because of an unparsed DMI, so
   27030 	       let's try again later.  */
   27031 	    return false;
   27032 	}
   27033       else if (!(added = !fns->add (fn)))
   27034 	{
   27035 	  /* If hash_set::add returns true, the element was already there.  */
   27036 	  location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
   27037 					    DECL_SOURCE_LOCATION (fn));
   27038 	  error_at (loc,
   27039 		    "exception specification of %qD depends on itself",
   27040 		    fn);
   27041 	  spec = noexcept_false_spec;
   27042 	}
   27043       else if (push_tinst_level (fn))
   27044 	{
   27045 	  const bool push_to_top = maybe_push_to_top_level (fn);
   27046 	  push_access_scope (fn);
   27047 	  push_deferring_access_checks (dk_no_deferred);
   27048 	  input_location = DECL_SOURCE_LOCATION (fn);
   27049 
   27050 	  if (DECL_IOBJ_MEMBER_FUNCTION_P (fn)
   27051 	      && !DECL_LOCAL_DECL_P (fn))
   27052 	    {
   27053 	      /* If needed, set current_class_ptr for the benefit of
   27054 		 tsubst_copy/PARM_DECL.  */
   27055 	      tree this_parm = DECL_ARGUMENTS (fn);
   27056 	      current_class_ptr = NULL_TREE;
   27057 	      current_class_ref = cp_build_fold_indirect_ref (this_parm);
   27058 	      current_class_ptr = this_parm;
   27059 	    }
   27060 
   27061 	  /* If this function is represented by a TEMPLATE_DECL, then
   27062 	     the deferred noexcept-specification might still contain
   27063 	     dependent types, even after substitution.  And we need the
   27064 	     dependency check functions to work in build_noexcept_spec.  */
   27065 	  if (orig_fn)
   27066 	    ++processing_template_decl;
   27067 
   27068 	  /* Do deferred instantiation of the noexcept-specifier.  */
   27069 	  noex = tsubst_expr (DEFERRED_NOEXCEPT_PATTERN (noex),
   27070 			      DEFERRED_NOEXCEPT_ARGS (noex),
   27071 			      tf_warning_or_error, fn);
   27072 	  /* Build up the noexcept-specification.  */
   27073 	  spec = build_noexcept_spec (noex, tf_warning_or_error);
   27074 
   27075 	  if (orig_fn)
   27076 	    --processing_template_decl;
   27077 
   27078 	  pop_deferring_access_checks ();
   27079 	  pop_access_scope (fn);
   27080 	  pop_tinst_level ();
   27081 	  maybe_pop_from_top_level (push_to_top);
   27082 	}
   27083       else
   27084 	spec = noexcept_false_spec;
   27085 
   27086       if (added)
   27087 	fns->remove (fn);
   27088     }
   27089 
   27090   if (spec == error_mark_node)
   27091     {
   27092       /* This failed with a hard error, so let's go with false.  */
   27093       gcc_assert (seen_error ());
   27094       spec = noexcept_false_spec;
   27095     }
   27096 
   27097   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
   27098   if (orig_fn)
   27099     TREE_TYPE (orig_fn) = TREE_TYPE (fn);
   27100 
   27101   return true;
   27102 }
   27103 
   27104 /* We're starting to process the function INST, an instantiation of PATTERN;
   27105    add their parameters to local_specializations.  */
   27106 
   27107 void
   27108 register_parameter_specializations (tree pattern, tree inst)
   27109 {
   27110   tree tmpl_parm = DECL_ARGUMENTS (pattern);
   27111   tree spec_parm = DECL_ARGUMENTS (inst);
   27112   if (DECL_IOBJ_MEMBER_FUNCTION_P (inst))
   27113     {
   27114       register_local_specialization (spec_parm, tmpl_parm);
   27115       spec_parm = skip_artificial_parms_for (inst, spec_parm);
   27116       tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
   27117     }
   27118   for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
   27119     {
   27120       if (!DECL_PACK_P (tmpl_parm))
   27121 	{
   27122 	  register_local_specialization (spec_parm, tmpl_parm);
   27123 	  spec_parm = DECL_CHAIN (spec_parm);
   27124 	}
   27125       else
   27126 	{
   27127 	  /* Register the (value) argument pack as a specialization of
   27128 	     TMPL_PARM, then move on.  */
   27129 	  tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
   27130 	  register_local_specialization (argpack, tmpl_parm);
   27131 	}
   27132     }
   27133   gcc_assert (!spec_parm);
   27134 }
   27135 
   27136 /* Instantiate the body of D using PATTERN with ARGS.  We have
   27137    already determined PATTERN is the correct template to use.
   27138    NESTED_P is true if this is a nested function, in which case
   27139    PATTERN will be a FUNCTION_DECL not a TEMPLATE_DECL.  */
   27140 
   27141 static void
   27142 instantiate_body (tree pattern, tree args, tree d, bool nested_p)
   27143 {
   27144   tree td = NULL_TREE;
   27145   tree code_pattern = pattern;
   27146 
   27147   if (!nested_p)
   27148     {
   27149       td = pattern;
   27150       code_pattern = DECL_TEMPLATE_RESULT (td);
   27151     }
   27152   else
   27153     /* Only OMP reductions are nested.  */
   27154     gcc_checking_assert (DECL_OMP_DECLARE_REDUCTION_P (code_pattern));
   27155 
   27156   vec<tree> omp_privatization_save;
   27157   if (current_function_decl)
   27158     save_omp_privatization_clauses (omp_privatization_save);
   27159 
   27160   bool push_to_top = maybe_push_to_top_level (d);
   27161 
   27162   mark_template_arguments_used (pattern, args);
   27163 
   27164   if (VAR_P (d))
   27165     {
   27166       /* The variable might be a lambda's extra scope, and that
   27167 	 lambda's visibility depends on D's.  */
   27168       maybe_commonize_var (d);
   27169       determine_visibility (d);
   27170     }
   27171 
   27172   /* Mark D as instantiated so that recursive calls to
   27173      instantiate_decl do not try to instantiate it again.  */
   27174   DECL_TEMPLATE_INSTANTIATED (d) = 1;
   27175 
   27176   if (td)
   27177     /* Regenerate the declaration in case the template has been modified
   27178        by a subsequent redeclaration.  */
   27179     regenerate_decl_from_template (d, td, args);
   27180 
   27181   /* We already set the file and line above.  Reset them now in case
   27182      they changed as a result of calling regenerate_decl_from_template.  */
   27183   input_location = DECL_SOURCE_LOCATION (d);
   27184 
   27185   if (VAR_P (d))
   27186     {
   27187       /* Clear out DECL_RTL; whatever was there before may not be right
   27188 	 since we've reset the type of the declaration.  */
   27189       SET_DECL_RTL (d, NULL);
   27190       DECL_IN_AGGR_P (d) = 0;
   27191 
   27192       /* The initializer is placed in DECL_INITIAL by
   27193 	 regenerate_decl_from_template so we don't need to
   27194 	 push/pop_access_scope again here.  Pull it out so that
   27195 	 cp_finish_decl can process it.  */
   27196       bool const_init = false;
   27197       tree init = DECL_INITIAL (d);
   27198       DECL_INITIAL (d) = NULL_TREE;
   27199       DECL_INITIALIZED_P (d) = 0;
   27200 
   27201       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
   27202 	 initializer.  That function will defer actual emission until
   27203 	 we have a chance to determine linkage.  */
   27204       DECL_EXTERNAL (d) = 0;
   27205 
   27206       /* Enter the scope of D so that access-checking works correctly.  */
   27207       bool enter_context = DECL_CLASS_SCOPE_P (d);
   27208       if (enter_context)
   27209         push_nested_class (DECL_CONTEXT (d));
   27210 
   27211       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
   27212       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
   27213 
   27214       if (enter_context)
   27215         pop_nested_class ();
   27216     }
   27217   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
   27218     synthesize_method (d);
   27219   else if (TREE_CODE (d) == FUNCTION_DECL)
   27220     {
   27221       /* Set up the list of local specializations.  */
   27222       local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
   27223       tree block = NULL_TREE;
   27224 
   27225       /* Set up context.  */
   27226       if (nested_p)
   27227 	block = push_stmt_list ();
   27228       else
   27229 	{
   27230 	  start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
   27231 
   27232 	  perform_instantiation_time_access_checks (code_pattern, args);
   27233 	}
   27234 
   27235       /* Create substitution entries for the parameters.  */
   27236       register_parameter_specializations (code_pattern, d);
   27237 
   27238       /* Substitute into the body of the function.  */
   27239       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
   27240 	tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
   27241 			tf_warning_or_error, d);
   27242       else
   27243 	{
   27244 	  tsubst_stmt (DECL_SAVED_TREE (code_pattern), args,
   27245 		       tf_warning_or_error, DECL_TI_TEMPLATE (d));
   27246 
   27247 	  /* Set the current input_location to the end of the function
   27248 	     so that finish_function knows where we are.  */
   27249 	  input_location
   27250 	    = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
   27251 
   27252 	  /* Remember if we saw an infinite loop in the template.  */
   27253 	  current_function_infinite_loop
   27254 	    = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
   27255 	}
   27256 
   27257       /* Finish the function.  */
   27258       if (nested_p)
   27259 	DECL_SAVED_TREE (d) = pop_stmt_list (block);
   27260       else
   27261 	{
   27262 	  d = finish_function (/*inline_p=*/false);
   27263 	  expand_or_defer_fn (d);
   27264 	}
   27265 
   27266       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
   27267 	cp_check_omp_declare_reduction (d);
   27268     }
   27269 
   27270   /* We're not deferring instantiation any more.  */
   27271   if (!nested_p)
   27272     TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
   27273 
   27274   maybe_pop_from_top_level (push_to_top);
   27275 
   27276   if (current_function_decl)
   27277     restore_omp_privatization_clauses (omp_privatization_save);
   27278 }
   27279 
   27280 /* Produce the definition of D, a _DECL generated from a template.  If
   27281    DEFER_OK is true, then we don't have to actually do the
   27282    instantiation now; we just have to do it sometime.  Normally it is
   27283    an error if this is an explicit instantiation but D is undefined.
   27284    EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
   27285    instantiated class template.  */
   27286 
   27287 tree
   27288 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
   27289 {
   27290   tree tmpl = DECL_TI_TEMPLATE (d);
   27291   tree gen_args;
   27292   tree args;
   27293   tree td;
   27294   tree code_pattern;
   27295   tree spec;
   27296   tree gen_tmpl;
   27297   bool pattern_defined;
   27298   location_t saved_loc = input_location;
   27299   bool external_p;
   27300   bool deleted_p;
   27301 
   27302   /* This function should only be used to instantiate templates for
   27303      functions and static member variables.  */
   27304   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
   27305 
   27306   /* A concept is never instantiated. */
   27307   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
   27308 
   27309   gcc_checking_assert (!DECL_FUNCTION_SCOPE_P (d));
   27310 
   27311   if (modules_p ())
   27312     /* We may have a pending instantiation of D itself.  */
   27313     lazy_load_pendings (d);
   27314 
   27315   /* Variables are never deferred; if instantiation is required, they
   27316      are instantiated right away.  That allows for better code in the
   27317      case that an expression refers to the value of the variable --
   27318      if the variable has a constant value the referring expression can
   27319      take advantage of that fact.  */
   27320   if (VAR_P (d))
   27321     defer_ok = false;
   27322 
   27323   /* Don't instantiate cloned functions.  Instead, instantiate the
   27324      functions they cloned.  */
   27325   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
   27326     d = DECL_CLONED_FUNCTION (d);
   27327 
   27328   if (DECL_TEMPLATE_INSTANTIATED (d)
   27329       || TREE_TYPE (d) == error_mark_node
   27330       || (TREE_CODE (d) == FUNCTION_DECL
   27331 	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
   27332       || DECL_TEMPLATE_SPECIALIZATION (d))
   27333     /* D has already been instantiated or explicitly specialized, so
   27334        there's nothing for us to do here.
   27335 
   27336        It might seem reasonable to check whether or not D is an explicit
   27337        instantiation, and, if so, stop here.  But when an explicit
   27338        instantiation is deferred until the end of the compilation,
   27339        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
   27340        the instantiation.  */
   27341     return d;
   27342 
   27343   /* Check to see whether we know that this template will be
   27344      instantiated in some other file, as with "extern template"
   27345      extension.  */
   27346   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
   27347 
   27348   /* In general, we do not instantiate such templates.  */
   27349   if (external_p && !always_instantiate_p (d))
   27350     return d;
   27351 
   27352   gen_tmpl = most_general_template (tmpl);
   27353   gen_args = DECL_TI_ARGS (d);
   27354 
   27355   /* We should already have the extra args.  */
   27356   gcc_checking_assert (tmpl == gen_tmpl
   27357 		       || (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
   27358 			   == TMPL_ARGS_DEPTH (gen_args)));
   27359   /* And what's in the hash table should match D.  */
   27360   gcc_checking_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0))
   27361 		       == d
   27362 		       || spec == NULL_TREE);
   27363 
   27364   /* This needs to happen before any tsubsting.  */
   27365   if (! push_tinst_level (d))
   27366     return d;
   27367 
   27368   auto_timevar tv (TV_TEMPLATE_INST);
   27369 
   27370   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
   27371      for the instantiation.  */
   27372   td = template_for_substitution (d);
   27373   args = gen_args;
   27374 
   27375   if (variable_template_specialization_p (d))
   27376     {
   27377       /* Look up an explicit specialization, if any.  */
   27378       tree partial_ti = most_specialized_partial_spec (d, tf_warning_or_error);
   27379       if (partial_ti && partial_ti != error_mark_node)
   27380 	{
   27381 	  td = TI_TEMPLATE (partial_ti);
   27382 	  args = TI_ARGS (partial_ti);
   27383 	}
   27384     }
   27385 
   27386   code_pattern = DECL_TEMPLATE_RESULT (td);
   27387 
   27388   /* We should never be trying to instantiate a member of a class
   27389      template or partial specialization.  */
   27390   gcc_assert (d != code_pattern);
   27391 
   27392   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
   27393       || DECL_TEMPLATE_SPECIALIZATION (td))
   27394     /* In the case of a friend template whose definition is provided
   27395        outside the class, we may have too many arguments.  Drop the
   27396        ones we don't need.  The same is true for specializations.  */
   27397     args = get_innermost_template_args
   27398       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
   27399 
   27400   if (TREE_CODE (d) == FUNCTION_DECL)
   27401     {
   27402       deleted_p = DECL_DELETED_FN (code_pattern);
   27403       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
   27404 			  && DECL_INITIAL (code_pattern) != error_mark_node)
   27405 			 || DECL_DEFAULTED_FN (code_pattern)
   27406 			 || deleted_p);
   27407     }
   27408   else
   27409     {
   27410       deleted_p = false;
   27411       if (DECL_CLASS_SCOPE_P (code_pattern))
   27412 	pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
   27413       else
   27414 	pattern_defined = ! DECL_EXTERNAL (code_pattern);
   27415     }
   27416 
   27417   /* We may be in the middle of deferred access check.  Disable it now.  */
   27418   push_deferring_access_checks (dk_no_deferred);
   27419 
   27420   /* Unless an explicit instantiation directive has already determined
   27421      the linkage of D, remember that a definition is available for
   27422      this entity.  */
   27423   if (pattern_defined
   27424       && !DECL_INTERFACE_KNOWN (d)
   27425       && !DECL_NOT_REALLY_EXTERN (d))
   27426     mark_definable (d);
   27427 
   27428   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
   27429   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
   27430   input_location = DECL_SOURCE_LOCATION (d);
   27431 
   27432   /* If D is a member of an explicitly instantiated class template,
   27433      and no definition is available, treat it like an implicit
   27434      instantiation.  */
   27435   if (!pattern_defined && expl_inst_class_mem_p
   27436       && DECL_EXPLICIT_INSTANTIATION (d))
   27437     {
   27438       /* Leave linkage flags alone on instantiations with anonymous
   27439 	 visibility.  */
   27440       if (TREE_PUBLIC (d))
   27441 	{
   27442 	  DECL_NOT_REALLY_EXTERN (d) = 0;
   27443 	  DECL_INTERFACE_KNOWN (d) = 0;
   27444 	}
   27445       SET_DECL_IMPLICIT_INSTANTIATION (d);
   27446     }
   27447 
   27448   /* Defer all other templates, unless we have been explicitly
   27449      forbidden from doing so.  */
   27450   if (/* If there is no definition, we cannot instantiate the
   27451 	 template.  */
   27452       ! pattern_defined
   27453       /* If it's OK to postpone instantiation, do so.  */
   27454       || defer_ok
   27455       /* If this is a static data member that will be defined
   27456 	 elsewhere, we don't want to instantiate the entire data
   27457 	 member, but we do want to instantiate the initializer so that
   27458 	 we can substitute that elsewhere.  */
   27459       || (external_p && VAR_P (d))
   27460       /* Handle here a deleted function too, avoid generating
   27461 	 its body (c++/61080).  */
   27462       || deleted_p)
   27463     {
   27464       /* The definition of the static data member is now required so
   27465 	 we must substitute the initializer.  */
   27466       if (VAR_P (d)
   27467 	  && !DECL_INITIAL (d)
   27468 	  && DECL_INITIAL (code_pattern))
   27469 	{
   27470 	  tree ns;
   27471 	  tree init;
   27472 	  bool const_init = false;
   27473 	  bool enter_context = DECL_CLASS_SCOPE_P (d);
   27474 
   27475 	  ns = decl_namespace_context (d);
   27476 	  push_nested_namespace (ns);
   27477 	  if (enter_context)
   27478 	    push_nested_class (DECL_CONTEXT (d));
   27479 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
   27480 			      args,
   27481 			      tf_warning_or_error, NULL_TREE);
   27482 	  /* If instantiating the initializer involved instantiating this
   27483 	     again, don't call cp_finish_decl twice.  */
   27484 	  if (!DECL_INITIAL (d))
   27485 	    {
   27486 	      /* Make sure the initializer is still constant, in case of
   27487 		 circular dependency (template/instantiate6.C). */
   27488 	      const_init
   27489 		= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
   27490 	      cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
   27491 			      /*asmspec_tree=*/NULL_TREE, 0);
   27492 	    }
   27493 	  if (enter_context)
   27494 	    pop_nested_class ();
   27495 	  pop_nested_namespace (ns);
   27496 	}
   27497 
   27498       /* We restore the source position here because it's used by
   27499 	 add_pending_template.  */
   27500       input_location = saved_loc;
   27501 
   27502       if (at_eof && !pattern_defined
   27503 	  && DECL_EXPLICIT_INSTANTIATION (d)
   27504 	  && DECL_NOT_REALLY_EXTERN (d))
   27505 	/* [temp.explicit]
   27506 
   27507 	   The definition of a non-exported function template, a
   27508 	   non-exported member function template, or a non-exported
   27509 	   member function or static data member of a class template
   27510 	   shall be present in every translation unit in which it is
   27511 	   explicitly instantiated.  */
   27512 	permerror (input_location,  "explicit instantiation of %qD "
   27513 		   "but no definition available", d);
   27514 
   27515       /* If we're in unevaluated context, we just wanted to get the
   27516 	 constant value; this isn't an odr use, so don't queue
   27517 	 a full instantiation.  */
   27518       if (!cp_unevaluated_operand
   27519 	  /* ??? Historically, we have instantiated inline functions, even
   27520 	     when marked as "extern template".  */
   27521 	  && !(external_p && VAR_P (d)))
   27522 	add_pending_template (d);
   27523     }
   27524   else
   27525     {
   27526       set_instantiating_module (d);
   27527       if (variable_template_p (gen_tmpl))
   27528 	note_vague_linkage_variable (d);
   27529       instantiate_body (td, args, d, false);
   27530     }
   27531 
   27532   pop_deferring_access_checks ();
   27533   pop_tinst_level ();
   27534   input_location = saved_loc;
   27535 
   27536   return d;
   27537 }
   27538 
   27539 /* Run through the list of templates that we wish we could
   27540    instantiate, and instantiate any we can.  RETRIES is the
   27541    number of times we retry pending template instantiation.  */
   27542 
   27543 void
   27544 instantiate_pending_templates (int retries)
   27545 {
   27546   int reconsider;
   27547   location_t saved_loc = input_location;
   27548 
   27549   /* Instantiating templates may trigger vtable generation.  This in turn
   27550      may require further template instantiations.  We place a limit here
   27551      to avoid infinite loop.  */
   27552   if (pending_templates && retries >= max_tinst_depth)
   27553     {
   27554       tree decl = pending_templates->tinst->maybe_get_node ();
   27555 
   27556       fatal_error (input_location,
   27557 		   "template instantiation depth exceeds maximum of %d"
   27558 		   " instantiating %q+D, possibly from virtual table generation"
   27559 		   " (use %<-ftemplate-depth=%> to increase the maximum)",
   27560 		   max_tinst_depth, decl);
   27561       if (TREE_CODE (decl) == FUNCTION_DECL)
   27562 	/* Pretend that we defined it.  */
   27563 	DECL_INITIAL (decl) = error_mark_node;
   27564       return;
   27565     }
   27566 
   27567   do
   27568     {
   27569       struct pending_template **t = &pending_templates;
   27570       struct pending_template *last = NULL;
   27571       reconsider = 0;
   27572       while (*t)
   27573 	{
   27574 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
   27575 	  bool complete = false;
   27576 
   27577 	  if (TYPE_P (instantiation))
   27578 	    {
   27579 	      if (!COMPLETE_TYPE_P (instantiation))
   27580 		{
   27581 		  instantiate_class_template (instantiation);
   27582 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
   27583 		    for (tree fld = TYPE_FIELDS (instantiation);
   27584 			 fld; fld = TREE_CHAIN (fld))
   27585 		      if ((VAR_P (fld)
   27586 			   || (TREE_CODE (fld) == FUNCTION_DECL
   27587 			       && !DECL_ARTIFICIAL (fld)))
   27588 			  && DECL_TEMPLATE_INSTANTIATION (fld))
   27589 			instantiate_decl (fld,
   27590 					  /*defer_ok=*/false,
   27591 					  /*expl_inst_class_mem_p=*/false);
   27592 
   27593 		  if (COMPLETE_TYPE_P (instantiation))
   27594 		    reconsider = 1;
   27595 		}
   27596 
   27597 	      complete = COMPLETE_TYPE_P (instantiation);
   27598 	    }
   27599 	  else
   27600 	    {
   27601 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
   27602 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
   27603 		{
   27604 		  instantiation
   27605 		    = instantiate_decl (instantiation,
   27606 					/*defer_ok=*/false,
   27607 					/*expl_inst_class_mem_p=*/false);
   27608 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
   27609 		    reconsider = 1;
   27610 		}
   27611 
   27612 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
   27613 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
   27614 	    }
   27615 
   27616 	  if (complete)
   27617 	    {
   27618 	      /* If INSTANTIATION has been instantiated, then we don't
   27619 		 need to consider it again in the future.  */
   27620 	      struct pending_template *drop = *t;
   27621 	      *t = (*t)->next;
   27622 	      set_refcount_ptr (drop->tinst);
   27623 	      pending_template_freelist ().free (drop);
   27624 	    }
   27625 	  else
   27626 	    {
   27627 	      last = *t;
   27628 	      t = &(*t)->next;
   27629 	    }
   27630 	  tinst_depth = 0;
   27631 	  set_refcount_ptr (current_tinst_level);
   27632 	}
   27633       last_pending_template = last;
   27634     }
   27635   while (reconsider);
   27636 
   27637   input_location = saved_loc;
   27638 }
   27639 
   27640 /* Substitute ARGVEC into T, which is a list of initializers for
   27641    either base class or a non-static data member.  The TREE_PURPOSEs
   27642    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
   27643    instantiate_decl.  */
   27644 
   27645 static tree
   27646 tsubst_initializer_list (tree t, tree argvec)
   27647 {
   27648   tree inits = NULL_TREE;
   27649   tree target_ctor = error_mark_node;
   27650 
   27651   for (; t; t = TREE_CHAIN (t))
   27652     {
   27653       tree decl;
   27654       tree init;
   27655       tree expanded_bases = NULL_TREE;
   27656       tree expanded_arguments = NULL_TREE;
   27657       int i, len = 1;
   27658 
   27659       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
   27660         {
   27661           tree expr;
   27662           tree arg;
   27663 
   27664           /* Expand the base class expansion type into separate base
   27665              classes.  */
   27666           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
   27667                                                  tf_warning_or_error,
   27668                                                  NULL_TREE);
   27669           if (expanded_bases == error_mark_node)
   27670             continue;
   27671 
   27672           /* We'll be building separate TREE_LISTs of arguments for
   27673              each base.  */
   27674           len = TREE_VEC_LENGTH (expanded_bases);
   27675           expanded_arguments = make_tree_vec (len);
   27676           for (i = 0; i < len; i++)
   27677             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
   27678 
   27679           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
   27680              expand each argument in the TREE_VALUE of t.  */
   27681           expr = make_node (EXPR_PACK_EXPANSION);
   27682 	  PACK_EXPANSION_LOCAL_P (expr) = true;
   27683           PACK_EXPANSION_PARAMETER_PACKS (expr) =
   27684             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
   27685 
   27686 	  if (TREE_VALUE (t) == void_type_node)
   27687 	    /* VOID_TYPE_NODE is used to indicate
   27688 	       value-initialization.  */
   27689 	    {
   27690 	      for (i = 0; i < len; i++)
   27691 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
   27692 	    }
   27693 	  else
   27694 	    {
   27695 	      /* Substitute parameter packs into each argument in the
   27696 		 TREE_LIST.  */
   27697 	      in_base_initializer = 1;
   27698 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
   27699 		{
   27700 		  tree expanded_exprs;
   27701 
   27702 		  /* Expand the argument.  */
   27703 		  tree value;
   27704 		  if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
   27705 		    value = TREE_VALUE (arg);
   27706 		  else
   27707 		    {
   27708 		      value = expr;
   27709 		      PACK_EXPANSION_PATTERN (value) = TREE_VALUE (arg);
   27710 		    }
   27711 		  expanded_exprs
   27712 		    = tsubst_pack_expansion (value, argvec,
   27713 					     tf_warning_or_error,
   27714 					     NULL_TREE);
   27715 		  if (expanded_exprs == error_mark_node)
   27716 		    continue;
   27717 
   27718 		  /* Prepend each of the expanded expressions to the
   27719 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
   27720 		  for (i = 0; i < len; i++)
   27721 		    if (TREE_CODE (TREE_VALUE (arg)) == EXPR_PACK_EXPANSION)
   27722 		      for (int j = 0; j < TREE_VEC_LENGTH (expanded_exprs); j++)
   27723 			TREE_VEC_ELT (expanded_arguments, i)
   27724 			  = tree_cons (NULL_TREE,
   27725 				       TREE_VEC_ELT (expanded_exprs, j),
   27726 				       TREE_VEC_ELT (expanded_arguments, i));
   27727 		    else
   27728 		      TREE_VEC_ELT (expanded_arguments, i)
   27729 			= tree_cons (NULL_TREE,
   27730 				     TREE_VEC_ELT (expanded_exprs, i),
   27731 				     TREE_VEC_ELT (expanded_arguments, i));
   27732 		}
   27733 	      in_base_initializer = 0;
   27734 
   27735 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
   27736 		 since we built them backwards.  */
   27737 	      for (i = 0; i < len; i++)
   27738 		{
   27739 		  TREE_VEC_ELT (expanded_arguments, i) =
   27740 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
   27741 		}
   27742 	    }
   27743         }
   27744 
   27745       for (i = 0; i < len; ++i)
   27746         {
   27747           if (expanded_bases)
   27748             {
   27749               decl = TREE_VEC_ELT (expanded_bases, i);
   27750               decl = expand_member_init (decl);
   27751               init = TREE_VEC_ELT (expanded_arguments, i);
   27752             }
   27753           else
   27754             {
   27755 	      tree tmp;
   27756 	      if (TYPE_P (TREE_PURPOSE (t)))
   27757 		decl = tsubst (TREE_PURPOSE (t), argvec,
   27758 			       tf_warning_or_error, NULL_TREE);
   27759 	      else
   27760 		decl = tsubst_expr (TREE_PURPOSE (t), argvec,
   27761 				    tf_warning_or_error, NULL_TREE);
   27762 
   27763               decl = expand_member_init (decl);
   27764               if (decl && !DECL_P (decl))
   27765                 in_base_initializer = 1;
   27766 
   27767 	      init = TREE_VALUE (t);
   27768 	      tmp = init;
   27769 	      if (init != void_type_node)
   27770 		init = tsubst_expr (init, argvec,
   27771 				    tf_warning_or_error, NULL_TREE);
   27772 	      if (init == NULL_TREE && tmp != NULL_TREE)
   27773 		/* If we had an initializer but it instantiated to nothing,
   27774 		   value-initialize the object.  This will only occur when
   27775 		   the initializer was a pack expansion where the parameter
   27776 		   packs used in that expansion were of length zero.  */
   27777 		init = void_type_node;
   27778               in_base_initializer = 0;
   27779             }
   27780 
   27781 	  if (target_ctor != error_mark_node
   27782 	      && init != error_mark_node)
   27783 	    {
   27784 	      error ("mem-initializer for %qD follows constructor delegation",
   27785 		     decl);
   27786 	      return inits;
   27787 	    }
   27788 	  /* Look for a target constructor. */
   27789 	  if (init != error_mark_node
   27790 	      && decl && CLASS_TYPE_P (decl)
   27791 	      && same_type_p (decl, current_class_type))
   27792 	    {
   27793 	      maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
   27794 	      if (inits)
   27795 		{
   27796 		  error ("constructor delegation follows mem-initializer for %qD",
   27797 			 TREE_PURPOSE (inits));
   27798 		  continue;
   27799 		}
   27800 	      target_ctor = init;
   27801 	    }
   27802 
   27803           if (decl)
   27804             {
   27805               init = build_tree_list (decl, init);
   27806 	      /* Carry over the dummy TREE_TYPE node containing the source
   27807 		 location.  */
   27808 	      TREE_TYPE (init) = TREE_TYPE (t);
   27809               TREE_CHAIN (init) = inits;
   27810               inits = init;
   27811             }
   27812         }
   27813     }
   27814   return inits;
   27815 }
   27816 
   27817 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
   27818    is the instantiation (which should have been created with
   27819    start_enum) and ARGS are the template arguments to use.  */
   27820 
   27821 static void
   27822 tsubst_enum (tree tag, tree newtag, tree args)
   27823 {
   27824   tree e;
   27825 
   27826   if (SCOPED_ENUM_P (newtag))
   27827     begin_scope (sk_scoped_enum, newtag);
   27828 
   27829   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
   27830     {
   27831       tree value;
   27832       tree decl = TREE_VALUE (e);
   27833 
   27834       /* Note that in a template enum, the TREE_VALUE is the
   27835 	 CONST_DECL, not the corresponding INTEGER_CST.  */
   27836       value = tsubst_expr (DECL_INITIAL (decl),
   27837 			   args, tf_warning_or_error, NULL_TREE);
   27838 
   27839       /* Give this enumeration constant the correct access.  */
   27840       set_current_access_from_decl (decl);
   27841 
   27842       /* Actually build the enumerator itself.  Here we're assuming that
   27843 	 enumerators can't have dependent attributes.  */
   27844       tree newdecl = build_enumerator (DECL_NAME (decl), value, newtag,
   27845 				       DECL_ATTRIBUTES (decl),
   27846 				       DECL_SOURCE_LOCATION (decl));
   27847       /* Attribute deprecated without an argument isn't sticky: it'll
   27848 	 melt into a tree flag, so we need to propagate the flag here,
   27849 	 since we just created a new enumerator.  */
   27850       TREE_DEPRECATED (newdecl) = TREE_DEPRECATED (decl);
   27851       TREE_UNAVAILABLE (newdecl) = TREE_UNAVAILABLE (decl);
   27852     }
   27853 
   27854   if (SCOPED_ENUM_P (newtag))
   27855     finish_scope ();
   27856 
   27857   finish_enum_value_list (newtag);
   27858   finish_enum (newtag);
   27859 
   27860   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
   27861     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
   27862   TREE_DEPRECATED (newtag) = TREE_DEPRECATED (tag);
   27863   TREE_UNAVAILABLE (newtag) = TREE_UNAVAILABLE (tag);
   27864 }
   27865 
   27866 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
   27867    its type -- but without substituting the innermost set of template
   27868    arguments.  So, innermost set of template parameters will appear in
   27869    the type.  */
   27870 
   27871 tree
   27872 get_mostly_instantiated_function_type (tree decl)
   27873 {
   27874   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
   27875   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
   27876 }
   27877 
   27878 /* Return truthvalue if we're processing a template different from
   27879    the last one involved in diagnostics.  */
   27880 bool
   27881 problematic_instantiation_changed (void)
   27882 {
   27883   return current_tinst_level != last_error_tinst_level;
   27884 }
   27885 
   27886 /* Remember current template involved in diagnostics.  */
   27887 void
   27888 record_last_problematic_instantiation (void)
   27889 {
   27890   set_refcount_ptr (last_error_tinst_level, current_tinst_level);
   27891 }
   27892 
   27893 struct tinst_level *
   27894 current_instantiation (void)
   27895 {
   27896   return current_tinst_level;
   27897 }
   27898 
   27899 /* Return TRUE if current_function_decl is being instantiated, false
   27900    otherwise.  */
   27901 
   27902 bool
   27903 instantiating_current_function_p (void)
   27904 {
   27905   return (current_instantiation ()
   27906 	  && (current_instantiation ()->maybe_get_node ()
   27907 	      == current_function_decl));
   27908 }
   27909 
   27910 /* [temp.param] Check that template non-type parm TYPE is of an allowable
   27911    type.  Return false for ok, true for disallowed.  Issue error and
   27912    inform messages under control of COMPLAIN.  */
   27913 
   27914 static bool
   27915 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
   27916 {
   27917   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
   27918     return false;
   27919   else if (TYPE_PTR_P (type))
   27920     return false;
   27921   else if (TYPE_REF_P (type)
   27922 	   && !TYPE_REF_IS_RVALUE (type))
   27923     return false;
   27924   else if (TYPE_PTRMEM_P (type))
   27925     return false;
   27926   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
   27927     {
   27928       if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx20)
   27929 	{
   27930 	  if (complain & tf_error)
   27931 	    error ("non-type template parameters of deduced class type only "
   27932 		   "available with %<-std=c++20%> or %<-std=gnu++20%>");
   27933 	  return true;
   27934 	}
   27935       return false;
   27936     }
   27937   else if (TREE_CODE (type) == NULLPTR_TYPE)
   27938     return false;
   27939   else if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM
   27940 	   && cxx_dialect < cxx11)
   27941     /* Fall through; before C++11 alias templates, a bound ttp
   27942        always instantiates into a class type.  */;
   27943   else if (WILDCARD_TYPE_P (type))
   27944     /* Any other wildcard type not already handled above is allowed.  */
   27945     return false;
   27946   else if (TREE_CODE (type) == COMPLEX_TYPE)
   27947     /* Fall through.  */;
   27948   else if (VOID_TYPE_P (type))
   27949     /* Fall through.  */;
   27950   else if (cxx_dialect >= cxx20)
   27951     {
   27952       if (dependent_type_p (type))
   27953 	return false;
   27954       if (!complete_type_or_maybe_complain (type, NULL_TREE, complain))
   27955 	return true;
   27956       if (structural_type_p (type))
   27957 	return false;
   27958       if (complain & tf_error)
   27959 	{
   27960 	  auto_diagnostic_group d;
   27961 	  error ("%qT is not a valid type for a template non-type "
   27962 		 "parameter because it is not structural", type);
   27963 	  structural_type_p (type, true);
   27964 	}
   27965       return true;
   27966     }
   27967   else if (CLASS_TYPE_P (type))
   27968     {
   27969       if (complain & tf_error)
   27970 	error ("non-type template parameters of class type only available "
   27971 	       "with %<-std=c++20%> or %<-std=gnu++20%>");
   27972       return true;
   27973     }
   27974 
   27975   if (complain & tf_error)
   27976     {
   27977       if (type == error_mark_node)
   27978 	inform (input_location, "invalid template non-type parameter");
   27979       else
   27980 	error ("%q#T is not a valid type for a template non-type parameter",
   27981 	       type);
   27982     }
   27983   return true;
   27984 }
   27985 
   27986 /* Returns true iff the noexcept-specifier for TYPE is value-dependent.  */
   27987 
   27988 static bool
   27989 value_dependent_noexcept_spec_p (tree type)
   27990 {
   27991   if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
   27992     if (tree noex = TREE_PURPOSE (spec))
   27993       /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
   27994 	 affect overload resolution and treating it as dependent breaks
   27995 	 things.  Same for an unparsed noexcept expression.  */
   27996       if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
   27997 	  && TREE_CODE (noex) != DEFERRED_PARSE
   27998 	  && value_dependent_expression_p (noex))
   27999 	return true;
   28000 
   28001   return false;
   28002 }
   28003 
   28004 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
   28005    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
   28006 
   28007 static bool
   28008 dependent_type_p_r (tree type)
   28009 {
   28010   tree scope;
   28011 
   28012   /* [temp.dep.type]
   28013 
   28014      A type is dependent if it is:
   28015 
   28016      -- a template parameter. Template template parameters are types
   28017 	for us (since TYPE_P holds true for them) so we handle
   28018 	them here.  */
   28019   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
   28020       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
   28021     return true;
   28022   /* -- a qualified-id with a nested-name-specifier which contains a
   28023 	class-name that names a dependent type or whose unqualified-id
   28024 	names a dependent type.  */
   28025   if (TREE_CODE (type) == TYPENAME_TYPE)
   28026     return true;
   28027 
   28028   /* An alias template specialization can be dependent even if the
   28029      resulting type is not.  */
   28030   if (dependent_alias_template_spec_p (type, nt_transparent))
   28031     return true;
   28032 
   28033   /* -- a cv-qualified type where the cv-unqualified type is
   28034 	dependent.
   28035      No code is necessary for this bullet; the code below handles
   28036      cv-qualified types, and we don't want to strip aliases with
   28037      TYPE_MAIN_VARIANT because of DR 1558.  */
   28038   /* -- a compound type constructed from any dependent type.  */
   28039   if (TYPE_PTRMEM_P (type))
   28040     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
   28041 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
   28042 					   (type)));
   28043   else if (INDIRECT_TYPE_P (type))
   28044     return dependent_type_p (TREE_TYPE (type));
   28045   else if (FUNC_OR_METHOD_TYPE_P (type))
   28046     {
   28047       tree arg_type;
   28048 
   28049       if (dependent_type_p (TREE_TYPE (type)))
   28050 	return true;
   28051       for (arg_type = TYPE_ARG_TYPES (type);
   28052 	   arg_type;
   28053 	   arg_type = TREE_CHAIN (arg_type))
   28054 	if (dependent_type_p (TREE_VALUE (arg_type)))
   28055 	  return true;
   28056       if (cxx_dialect >= cxx17
   28057 	  && value_dependent_noexcept_spec_p (type))
   28058 	/* A value-dependent noexcept-specifier makes the type dependent.  */
   28059 	return true;
   28060       return false;
   28061     }
   28062   /* -- an array type constructed from any dependent type or whose
   28063 	size is specified by a constant expression that is
   28064 	value-dependent.
   28065 
   28066         We checked for type- and value-dependence of the bounds in
   28067         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
   28068   if (TREE_CODE (type) == ARRAY_TYPE)
   28069     {
   28070       if (TYPE_DOMAIN (type)
   28071 	  && dependent_type_p (TYPE_DOMAIN (type)))
   28072 	return true;
   28073       return dependent_type_p (TREE_TYPE (type));
   28074     }
   28075 
   28076   /* -- a template-id in which either the template name is a template
   28077      parameter ...  */
   28078   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
   28079     return true;
   28080   /* ... or any of the template arguments is a dependent type or
   28081 	an expression that is type-dependent or value-dependent.  */
   28082   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
   28083 	   && (any_dependent_template_arguments_p
   28084 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
   28085     return true;
   28086 
   28087   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and TRAIT_TYPEs are
   28088      dependent; if the argument of the `typeof' expression is not
   28089      type-dependent, then it should already been have resolved.  */
   28090   if (TREE_CODE (type) == TYPEOF_TYPE
   28091       || TREE_CODE (type) == DECLTYPE_TYPE
   28092       || TREE_CODE (type) == TRAIT_TYPE)
   28093     return true;
   28094 
   28095   /* A template argument pack is dependent if any of its packed
   28096      arguments are.  */
   28097   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
   28098     {
   28099       tree args = ARGUMENT_PACK_ARGS (type);
   28100       for (tree arg : tree_vec_range (args))
   28101 	if (dependent_template_arg_p (arg))
   28102 	  return true;
   28103     }
   28104 
   28105   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
   28106      be template parameters.  */
   28107   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
   28108     return true;
   28109 
   28110   if (TREE_CODE (type) == DEPENDENT_OPERATOR_TYPE)
   28111     return true;
   28112 
   28113   if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
   28114     return true;
   28115 
   28116   /* The standard does not specifically mention types that are local
   28117      to template functions or local classes, but they should be
   28118      considered dependent too.  For example:
   28119 
   28120        template <int I> void f() {
   28121 	 enum E { a = I };
   28122 	 S<sizeof (E)> s;
   28123        }
   28124 
   28125      The size of `E' cannot be known until the value of `I' has been
   28126      determined.  Therefore, `E' must be considered dependent.  */
   28127   scope = TYPE_CONTEXT (type);
   28128   if (scope && TYPE_P (scope))
   28129     return dependent_type_p (scope);
   28130   /* Don't use type_dependent_expression_p here, as it can lead
   28131      to infinite recursion trying to determine whether a lambda
   28132      nested in a lambda is dependent (c++/47687).  */
   28133   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
   28134 	   && DECL_LANG_SPECIFIC (scope)
   28135 	   && DECL_TEMPLATE_INFO (scope)
   28136 	   && (any_dependent_template_arguments_p
   28137 	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
   28138     return true;
   28139 
   28140   /* Other types are non-dependent.  */
   28141   return false;
   28142 }
   28143 
   28144 /* Returns TRUE if TYPE is dependent, in the sense of
   28145    [temp.dep.type].  Note that a NULL type is considered dependent.  */
   28146 
   28147 bool
   28148 dependent_type_p (tree type)
   28149 {
   28150   /* If there are no template parameters in scope, then there can't be
   28151      any dependent types.  */
   28152   if (!processing_template_decl)
   28153     {
   28154       /* If we are not processing a template, then nobody should be
   28155 	 providing us with a dependent type.  */
   28156       gcc_assert (type);
   28157       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
   28158       return false;
   28159     }
   28160 
   28161   /* If the type is NULL, we have not computed a type for the entity
   28162      in question; in that case, the type is dependent.  */
   28163   if (!type)
   28164     return true;
   28165 
   28166   /* Erroneous types can be considered non-dependent.  */
   28167   if (type == error_mark_node)
   28168     return false;
   28169 
   28170   /* If we have not already computed the appropriate value for TYPE,
   28171      do so now.  */
   28172   if (!TYPE_DEPENDENT_P_VALID (type))
   28173     {
   28174       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
   28175       TYPE_DEPENDENT_P_VALID (type) = 1;
   28176     }
   28177 
   28178   return TYPE_DEPENDENT_P (type);
   28179 }
   28180 
   28181 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
   28182    lookup.  In other words, a dependent type that is not the current
   28183    instantiation.  */
   28184 
   28185 bool
   28186 dependent_scope_p (tree scope)
   28187 {
   28188   return (scope && TYPE_P (scope) && dependent_type_p (scope)
   28189 	  && !currently_open_class (scope));
   28190 }
   28191 
   28192 /* True if we might find more declarations in SCOPE during instantiation than
   28193    we can when parsing the template.  */
   28194 
   28195 bool
   28196 dependentish_scope_p (tree scope)
   28197 {
   28198   return dependent_scope_p (scope) || any_dependent_bases_p (scope);
   28199 }
   28200 
   28201 /* T is a SCOPE_REF.  Return whether it represents a non-static member of
   28202    an unknown base of 'this' (and is therefore instantiation-dependent).  */
   28203 
   28204 static bool
   28205 unknown_base_ref_p (tree t)
   28206 {
   28207   if (!current_class_ptr)
   28208     return false;
   28209 
   28210   tree mem = TREE_OPERAND (t, 1);
   28211   if (shared_member_p (mem))
   28212     return false;
   28213 
   28214   tree cur = current_nonlambda_class_type ();
   28215   if (!any_dependent_bases_p (cur))
   28216     return false;
   28217 
   28218   tree ctx = TREE_OPERAND (t, 0);
   28219   if (DERIVED_FROM_P (ctx, cur))
   28220     return false;
   28221 
   28222   return true;
   28223 }
   28224 
   28225 /* T is a SCOPE_REF; return whether we need to consider it
   28226     instantiation-dependent so that we can check access at instantiation
   28227     time even though we know which member it resolves to.  */
   28228 
   28229 static bool
   28230 instantiation_dependent_scope_ref_p (tree t)
   28231 {
   28232   if (DECL_P (TREE_OPERAND (t, 1))
   28233       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
   28234       && !dependent_scope_p (TREE_OPERAND (t, 0))
   28235       && !unknown_base_ref_p (t)
   28236       && accessible_in_template_p (TREE_OPERAND (t, 0),
   28237 				   TREE_OPERAND (t, 1)))
   28238     return false;
   28239   else
   28240     return true;
   28241 }
   28242 
   28243 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
   28244    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
   28245    expression.  */
   28246 
   28247 /* Note that this predicate is not appropriate for general expressions;
   28248    only constant expressions (that satisfy potential_constant_expression)
   28249    can be tested for value dependence.  */
   28250 
   28251 bool
   28252 value_dependent_expression_p (tree expression)
   28253 {
   28254   if (!processing_template_decl || expression == NULL_TREE)
   28255     return false;
   28256 
   28257   /* A type-dependent expression is also value-dependent.  */
   28258   if (type_dependent_expression_p (expression))
   28259     return true;
   28260 
   28261   switch (TREE_CODE (expression))
   28262     {
   28263     case BASELINK:
   28264       /* A dependent member function of the current instantiation.  */
   28265       return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
   28266 
   28267     case FUNCTION_DECL:
   28268       /* A dependent member function of the current instantiation.  */
   28269       if (DECL_CLASS_SCOPE_P (expression)
   28270 	  && dependent_type_p (DECL_CONTEXT (expression)))
   28271 	return true;
   28272       break;
   28273 
   28274     case IDENTIFIER_NODE:
   28275       /* A name that has not been looked up -- must be dependent.  */
   28276       return true;
   28277 
   28278     case TEMPLATE_PARM_INDEX:
   28279       /* A non-type template parm.  */
   28280       return true;
   28281 
   28282     case CONST_DECL:
   28283       /* A non-type template parm.  */
   28284       if (DECL_TEMPLATE_PARM_P (expression))
   28285 	return true;
   28286       return value_dependent_expression_p (DECL_INITIAL (expression));
   28287 
   28288     case VAR_DECL:
   28289        /* A constant with literal type and is initialized
   28290 	  with an expression that is value-dependent.  */
   28291       if (DECL_DEPENDENT_INIT_P (expression))
   28292 	return true;
   28293       if (DECL_HAS_VALUE_EXPR_P (expression))
   28294 	{
   28295 	  tree value_expr = DECL_VALUE_EXPR (expression);
   28296 	  if (value_dependent_expression_p (value_expr)
   28297 	      /* __PRETTY_FUNCTION__ inside a template function is dependent
   28298 		 on the name of the function.  */
   28299 	      || (DECL_PRETTY_FUNCTION_P (expression)
   28300 		  /* It might be used in a template, but not a template
   28301 		     function, in which case its DECL_VALUE_EXPR will be
   28302 		     "top level".  */
   28303 		  && value_expr == error_mark_node))
   28304 	    return true;
   28305 	}
   28306       else if (TYPE_REF_P (TREE_TYPE (expression)))
   28307 	/* FIXME cp_finish_decl doesn't fold reference initializers.  */
   28308 	return true;
   28309       /* We have a constexpr variable and we're processing a template.  When
   28310 	 there's lifetime extension involved (for which finish_compound_literal
   28311 	 used to create a temporary), we'll not be able to evaluate the
   28312 	 variable until instantiating, so pretend it's value-dependent.  */
   28313       else if (DECL_DECLARED_CONSTEXPR_P (expression)
   28314 	       && !TREE_CONSTANT (expression))
   28315 	return true;
   28316       return false;
   28317 
   28318     case DYNAMIC_CAST_EXPR:
   28319     case STATIC_CAST_EXPR:
   28320     case CONST_CAST_EXPR:
   28321     case REINTERPRET_CAST_EXPR:
   28322     case CAST_EXPR:
   28323     case IMPLICIT_CONV_EXPR:
   28324       /* These expressions are value-dependent if the type to which
   28325 	 the cast occurs is dependent or the expression being casted
   28326 	 is value-dependent.  */
   28327       {
   28328 	tree type = TREE_TYPE (expression);
   28329 
   28330 	if (dependent_type_p (type))
   28331 	  return true;
   28332 
   28333 	/* A functional cast has a list of operands.  */
   28334 	expression = TREE_OPERAND (expression, 0);
   28335 	if (!expression)
   28336 	  {
   28337 	    /* If there are no operands, it must be an expression such
   28338 	       as "int()". This should not happen for aggregate types
   28339 	       because it would form non-constant expressions.  */
   28340 	    gcc_assert (cxx_dialect >= cxx11
   28341 			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
   28342 
   28343 	    return false;
   28344 	  }
   28345 
   28346 	if (TREE_CODE (expression) == TREE_LIST)
   28347 	  return any_value_dependent_elements_p (expression);
   28348 
   28349 	if (TREE_CODE (type) == REFERENCE_TYPE
   28350 	    && has_value_dependent_address (expression))
   28351 	  return true;
   28352 
   28353 	return value_dependent_expression_p (expression);
   28354       }
   28355 
   28356     case SIZEOF_EXPR:
   28357       if (SIZEOF_EXPR_TYPE_P (expression))
   28358 	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
   28359       /* FALLTHRU */
   28360     case ALIGNOF_EXPR:
   28361     case TYPEID_EXPR:
   28362       /* A `sizeof' expression is value-dependent if the operand is
   28363 	 type-dependent or is a pack expansion.  */
   28364       expression = TREE_OPERAND (expression, 0);
   28365       if (PACK_EXPANSION_P (expression))
   28366         return true;
   28367       else if (TYPE_P (expression))
   28368 	return dependent_type_p (expression);
   28369       return instantiation_dependent_uneval_expression_p (expression);
   28370 
   28371     case AT_ENCODE_EXPR:
   28372       /* An 'encode' expression is value-dependent if the operand is
   28373 	 type-dependent.  */
   28374       expression = TREE_OPERAND (expression, 0);
   28375       return dependent_type_p (expression);
   28376 
   28377     case NOEXCEPT_EXPR:
   28378       expression = TREE_OPERAND (expression, 0);
   28379       return instantiation_dependent_uneval_expression_p (expression);
   28380 
   28381     case SCOPE_REF:
   28382       /* All instantiation-dependent expressions should also be considered
   28383 	 value-dependent.  */
   28384       return instantiation_dependent_scope_ref_p (expression);
   28385 
   28386     case COMPONENT_REF:
   28387       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
   28388 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
   28389 
   28390     case NONTYPE_ARGUMENT_PACK:
   28391       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
   28392          is value-dependent.  */
   28393       for (tree arg : tree_vec_range (ARGUMENT_PACK_ARGS (expression)))
   28394 	if (value_dependent_expression_p (arg))
   28395 	  return true;
   28396       return false;
   28397 
   28398     case TRAIT_EXPR:
   28399       {
   28400 	if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
   28401 	  return true;
   28402 
   28403 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
   28404 	if (!type2)
   28405 	  return false;
   28406 
   28407 	if (TREE_CODE (type2) != TREE_VEC)
   28408 	  return dependent_type_p (type2);
   28409 
   28410 	for (tree arg : tree_vec_range (type2))
   28411 	  if (dependent_type_p (arg))
   28412 	    return true;
   28413 
   28414 	return false;
   28415       }
   28416 
   28417     case MODOP_EXPR:
   28418       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
   28419 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
   28420 
   28421     case ARRAY_REF:
   28422       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
   28423 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
   28424 
   28425     case ADDR_EXPR:
   28426       {
   28427 	tree op = TREE_OPERAND (expression, 0);
   28428 	return (value_dependent_expression_p (op)
   28429 		|| has_value_dependent_address (op));
   28430       }
   28431 
   28432     case REQUIRES_EXPR:
   28433       /* Treat all requires-expressions as value-dependent so
   28434          we don't try to fold them.  */
   28435       return true;
   28436 
   28437     case TYPE_REQ:
   28438       return dependent_type_p (TREE_OPERAND (expression, 0));
   28439 
   28440     case CALL_EXPR:
   28441       {
   28442 	if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
   28443 	  return true;
   28444 	tree fn = get_callee_fndecl (expression);
   28445 	int i, nargs;
   28446 	nargs = call_expr_nargs (expression);
   28447 	for (i = 0; i < nargs; ++i)
   28448 	  {
   28449 	    tree op = CALL_EXPR_ARG (expression, i);
   28450 	    /* In a call to a constexpr member function, look through the
   28451 	       implicit ADDR_EXPR on the object argument so that it doesn't
   28452 	       cause the call to be considered value-dependent.  We also
   28453 	       look through it in potential_constant_expression.  */
   28454 	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
   28455 		&& DECL_IOBJ_MEMBER_FUNCTION_P (fn)
   28456 		&& TREE_CODE (op) == ADDR_EXPR)
   28457 	      op = TREE_OPERAND (op, 0);
   28458 	    if (value_dependent_expression_p (op))
   28459 	      return true;
   28460 	  }
   28461 	return false;
   28462       }
   28463 
   28464     case TEMPLATE_ID_EXPR:
   28465       return concept_definition_p (TREE_OPERAND (expression, 0))
   28466 	&& any_dependent_template_arguments_p (TREE_OPERAND (expression, 1));
   28467 
   28468     case CONSTRUCTOR:
   28469       {
   28470 	unsigned ix;
   28471 	tree val;
   28472 	if (dependent_type_p (TREE_TYPE (expression)))
   28473 	  return true;
   28474 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
   28475 	  if (value_dependent_expression_p (val))
   28476 	    return true;
   28477 	return false;
   28478       }
   28479 
   28480     case STMT_EXPR:
   28481       /* Treat a GNU statement expression as dependent to avoid crashing
   28482 	 under instantiate_non_dependent_expr; it can't be constant.  */
   28483       return true;
   28484 
   28485     case NEW_EXPR:
   28486     case VEC_NEW_EXPR:
   28487       /* The second operand is a type, which type_dependent_expression_p
   28488 	 (and therefore value_dependent_expression_p) doesn't want to see.  */
   28489       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
   28490 	      || value_dependent_expression_p (TREE_OPERAND (expression, 2))
   28491 	      || value_dependent_expression_p (TREE_OPERAND (expression, 3)));
   28492 
   28493     default:
   28494       /* A constant expression is value-dependent if any subexpression is
   28495 	 value-dependent.  */
   28496       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
   28497 	{
   28498 	case tcc_reference:
   28499 	case tcc_unary:
   28500 	case tcc_comparison:
   28501 	case tcc_binary:
   28502 	case tcc_expression:
   28503 	case tcc_vl_exp:
   28504 	  {
   28505 	    int i, len = cp_tree_operand_length (expression);
   28506 
   28507 	    for (i = 0; i < len; i++)
   28508 	      {
   28509 		tree t = TREE_OPERAND (expression, i);
   28510 
   28511 		/* In some cases, some of the operands may be missing.
   28512 		   (For example, in the case of PREDECREMENT_EXPR, the
   28513 		   amount to increment by may be missing.)  That doesn't
   28514 		   make the expression dependent.  */
   28515 		if (t && value_dependent_expression_p (t))
   28516 		  return true;
   28517 	      }
   28518 	  }
   28519 	  break;
   28520 	default:
   28521 	  break;
   28522 	}
   28523       break;
   28524     }
   28525 
   28526   /* The expression is not value-dependent.  */
   28527   return false;
   28528 }
   28529 
   28530 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
   28531    [temp.dep.expr].  Note that an expression with no type is
   28532    considered dependent.  Other parts of the compiler arrange for an
   28533    expression with type-dependent subexpressions to have no type, so
   28534    this function doesn't have to be fully recursive.  */
   28535 
   28536 bool
   28537 type_dependent_expression_p (tree expression)
   28538 {
   28539   if (!processing_template_decl)
   28540     return false;
   28541 
   28542   if (expression == NULL_TREE || expression == error_mark_node)
   28543     return false;
   28544 
   28545   gcc_checking_assert (!TYPE_P (expression));
   28546 
   28547   STRIP_ANY_LOCATION_WRAPPER (expression);
   28548 
   28549   /* An unresolved name is always dependent.  */
   28550   if (identifier_p (expression)
   28551       || TREE_CODE (expression) == USING_DECL
   28552       || TREE_CODE (expression) == WILDCARD_DECL)
   28553     return true;
   28554 
   28555   /* A lambda-expression in template context is dependent.  dependent_type_p is
   28556      true for a lambda in the scope of a class or function template, but that
   28557      doesn't cover all template contexts, like a default template argument.  */
   28558   if (TREE_CODE (expression) == LAMBDA_EXPR)
   28559     return true;
   28560 
   28561   /* A fold expression is type-dependent. */
   28562   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
   28563       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
   28564       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
   28565       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
   28566     return true;
   28567 
   28568   /* Some expression forms are never type-dependent.  */
   28569   if (TREE_CODE (expression) == SIZEOF_EXPR
   28570       || TREE_CODE (expression) == ALIGNOF_EXPR
   28571       || TREE_CODE (expression) == AT_ENCODE_EXPR
   28572       || TREE_CODE (expression) == NOEXCEPT_EXPR
   28573       || TREE_CODE (expression) == TRAIT_EXPR
   28574       || TREE_CODE (expression) == TYPEID_EXPR
   28575       || TREE_CODE (expression) == DELETE_EXPR
   28576       || TREE_CODE (expression) == VEC_DELETE_EXPR
   28577       || TREE_CODE (expression) == THROW_EXPR
   28578       || TREE_CODE (expression) == REQUIRES_EXPR)
   28579     return false;
   28580 
   28581   /* The types of these expressions depends only on the type to which
   28582      the cast occurs.  */
   28583   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
   28584       || TREE_CODE (expression) == STATIC_CAST_EXPR
   28585       || TREE_CODE (expression) == CONST_CAST_EXPR
   28586       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
   28587       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
   28588       || TREE_CODE (expression) == CAST_EXPR)
   28589     return dependent_type_p (TREE_TYPE (expression));
   28590 
   28591   /* The types of these expressions depends only on the type created
   28592      by the expression.  */
   28593   if (TREE_CODE (expression) == NEW_EXPR
   28594       || TREE_CODE (expression) == VEC_NEW_EXPR)
   28595     {
   28596       /* For NEW_EXPR tree nodes created inside a template, either
   28597 	 the object type itself or a TREE_LIST may appear as the
   28598 	 operand 1.  */
   28599       tree type = TREE_OPERAND (expression, 1);
   28600       if (TREE_CODE (type) == TREE_LIST)
   28601 	/* This is an array type.  We need to check array dimensions
   28602 	   as well.  */
   28603 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
   28604 	       || value_dependent_expression_p
   28605 		    (TREE_OPERAND (TREE_VALUE (type), 1));
   28606       /* Array type whose dimension has to be deduced.  */
   28607       else if (TREE_CODE (type) == ARRAY_TYPE
   28608 	       && TREE_OPERAND (expression, 2) == NULL_TREE)
   28609 	return true;
   28610       else
   28611 	return dependent_type_p (type);
   28612     }
   28613 
   28614   if (TREE_CODE (expression) == SCOPE_REF)
   28615     {
   28616       tree scope = TREE_OPERAND (expression, 0);
   28617       tree name = TREE_OPERAND (expression, 1);
   28618 
   28619       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
   28620 	 contains an identifier associated by name lookup with one or more
   28621 	 declarations declared with a dependent type, or...a
   28622 	 nested-name-specifier or qualified-id that names a member of an
   28623 	 unknown specialization.  */
   28624       return (type_dependent_expression_p (name)
   28625 	      || dependent_scope_p (scope));
   28626     }
   28627 
   28628   if (TREE_CODE (expression) == TEMPLATE_DECL
   28629       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
   28630     return uses_outer_template_parms (expression);
   28631 
   28632   if (TREE_CODE (expression) == STMT_EXPR)
   28633     expression = stmt_expr_value_expr (expression);
   28634 
   28635   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
   28636     {
   28637       for (auto &elt : CONSTRUCTOR_ELTS (expression))
   28638 	if (type_dependent_expression_p (elt.value))
   28639 	  return true;
   28640       return false;
   28641     }
   28642 
   28643   /* A static data member of the current instantiation with incomplete
   28644      array type is type-dependent, as the definition and specializations
   28645      can have different bounds.  */
   28646   if (VAR_P (expression)
   28647       && DECL_CLASS_SCOPE_P (expression)
   28648       && dependent_type_p (DECL_CONTEXT (expression))
   28649       && VAR_HAD_UNKNOWN_BOUND (expression))
   28650     return true;
   28651 
   28652   /* An array of unknown bound depending on a variadic parameter, eg:
   28653 
   28654      template<typename... Args>
   28655        void foo (Args... args)
   28656        {
   28657          int arr[] = { args... };
   28658        }
   28659 
   28660      template<int... vals>
   28661        void bar ()
   28662        {
   28663          int arr[] = { vals... };
   28664        }
   28665 
   28666      If the array has no length and has an initializer, it must be that
   28667      we couldn't determine its length in cp_complete_array_type because
   28668      it is dependent.  */
   28669   if (((VAR_P (expression) && DECL_INITIAL (expression))
   28670        || COMPOUND_LITERAL_P (expression))
   28671       && TREE_TYPE (expression) != NULL_TREE
   28672       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
   28673       && !TYPE_DOMAIN (TREE_TYPE (expression)))
   28674    return true;
   28675 
   28676   /* Pull a FUNCTION_DECL out of a BASELINK if we can.  */
   28677   if (BASELINK_P (expression))
   28678     {
   28679       if (BASELINK_OPTYPE (expression)
   28680 	  && dependent_type_p (BASELINK_OPTYPE (expression)))
   28681 	return true;
   28682       expression = BASELINK_FUNCTIONS (expression);
   28683     }
   28684 
   28685   /* A function or variable template-id is type-dependent if it has any
   28686      dependent template arguments.  */
   28687   if (VAR_OR_FUNCTION_DECL_P (expression)
   28688       && DECL_LANG_SPECIFIC (expression)
   28689       && DECL_TEMPLATE_INFO (expression))
   28690     {
   28691       /* Consider the innermost template arguments, since those are the ones
   28692 	 that come from the template-id; the template arguments for the
   28693 	 enclosing class do not make it type-dependent unless they are used in
   28694 	 the type of the decl.  */
   28695       if (instantiates_primary_template_p (expression)
   28696 	  && (any_dependent_template_arguments_p
   28697 	      (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
   28698 	return true;
   28699     }
   28700 
   28701   /* Otherwise, if the function decl isn't from a dependent scope, it can't be
   28702      type-dependent.  Checking this is important for functions with auto return
   28703      type, which looks like a dependent type.  */
   28704   if (TREE_CODE (expression) == FUNCTION_DECL
   28705       && !(DECL_CLASS_SCOPE_P (expression)
   28706 	   && dependent_type_p (DECL_CONTEXT (expression)))
   28707       && !(DECL_LANG_SPECIFIC (expression)
   28708 	   && DECL_UNIQUE_FRIEND_P (expression)
   28709 	   && (!DECL_FRIEND_CONTEXT (expression)
   28710 	       || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
   28711       && !DECL_LOCAL_DECL_P (expression))
   28712     {
   28713       gcc_assert (!dependent_type_p (TREE_TYPE (expression))
   28714 		  || undeduced_auto_decl (expression));
   28715       return false;
   28716     }
   28717 
   28718   /* Otherwise, its constraints could still depend on outer template parameters
   28719      from its (dependent) scope.  */
   28720   if (TREE_CODE (expression) == FUNCTION_DECL
   28721       /* As an optimization, check this cheaper sufficient condition first.
   28722 	 (At this point we've established that we're looking at a member of
   28723 	 a dependent class, so it makes sense to start treating say undeduced
   28724 	 auto as dependent.)  */
   28725       && !dependent_type_p (TREE_TYPE (expression))
   28726       && uses_outer_template_parms_in_constraints (expression))
   28727     return true;
   28728 
   28729   /* Always dependent, on the number of arguments if nothing else.  */
   28730   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
   28731     return true;
   28732 
   28733   if (TREE_TYPE (expression) == unknown_type_node)
   28734     {
   28735       if (TREE_CODE (expression) == ADDR_EXPR)
   28736 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
   28737       if (TREE_CODE (expression) == COMPONENT_REF
   28738 	  || TREE_CODE (expression) == OFFSET_REF)
   28739 	{
   28740 	  if (type_dependent_object_expression_p (TREE_OPERAND (expression, 0)))
   28741 	    return true;
   28742 	  expression = TREE_OPERAND (expression, 1);
   28743 	  if (identifier_p (expression))
   28744 	    return false;
   28745 	}
   28746       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
   28747       if (TREE_CODE (expression) == SCOPE_REF)
   28748 	return false;
   28749 
   28750       if (BASELINK_P (expression))
   28751 	{
   28752 	  if (BASELINK_OPTYPE (expression)
   28753 	      && dependent_type_p (BASELINK_OPTYPE (expression)))
   28754 	    return true;
   28755 	  expression = BASELINK_FUNCTIONS (expression);
   28756 	}
   28757 
   28758       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
   28759 	{
   28760 	  tree args = TREE_OPERAND (expression, 1);
   28761 	  if (any_dependent_template_arguments_p (args))
   28762 	    return true;
   28763 	  /* Arguments of a function template-id aren't necessarily coerced
   28764 	     yet so we must conservatively assume that the address (and not
   28765 	     just value) of the argument matters as per [temp.dep.temp]/3.  */
   28766 	  for (tree arg : tree_vec_range (args))
   28767 	    if (has_value_dependent_address (arg))
   28768 	      return true;
   28769 	  expression = TREE_OPERAND (expression, 0);
   28770 	  if (identifier_p (expression))
   28771 	    return true;
   28772 	}
   28773 
   28774       gcc_assert (OVL_P (expression));
   28775 
   28776       for (lkp_iterator iter (expression); iter; ++iter)
   28777 	if (type_dependent_expression_p (*iter))
   28778 	  return true;
   28779 
   28780       return false;
   28781     }
   28782 
   28783   /* The type of a non-type template parm declared with a placeholder type
   28784      depends on the corresponding template argument, even though
   28785      placeholders are not normally considered dependent.  */
   28786   if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
   28787       && is_auto (TREE_TYPE (expression)))
   28788     return true;
   28789 
   28790   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
   28791 
   28792   /* Dependent type attributes might not have made it from the decl to
   28793      the type yet.  */
   28794   if (DECL_P (expression)
   28795       && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
   28796     return true;
   28797 
   28798   return (dependent_type_p (TREE_TYPE (expression)));
   28799 }
   28800 
   28801 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
   28802    type-dependent if the expression refers to a member of the current
   28803    instantiation and the type of the referenced member is dependent, or the
   28804    class member access expression refers to a member of an unknown
   28805    specialization.
   28806 
   28807    This function returns true if the OBJECT in such a class member access
   28808    expression is of an unknown specialization.  */
   28809 
   28810 bool
   28811 type_dependent_object_expression_p (tree object)
   28812 {
   28813   /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
   28814      dependent.  */
   28815   if (TREE_CODE (object) == IDENTIFIER_NODE)
   28816     return true;
   28817   tree scope = TREE_TYPE (object);
   28818   return (!scope || dependent_scope_p (scope));
   28819 }
   28820 
   28821 /* walk_tree callback function for instantiation_dependent_expression_p,
   28822    below.  Returns non-zero if a dependent subexpression is found.  */
   28823 
   28824 static tree
   28825 instantiation_dependent_r (tree *tp, int *walk_subtrees,
   28826 			   void * /*data*/)
   28827 {
   28828   if (TYPE_P (*tp))
   28829     {
   28830       /* We don't have to worry about decltype currently because decltype
   28831 	 of an instantiation-dependent expr is a dependent type.  This
   28832 	 might change depending on the resolution of DR 1172.  */
   28833       *walk_subtrees = false;
   28834       return NULL_TREE;
   28835     }
   28836   enum tree_code code = TREE_CODE (*tp);
   28837   switch (code)
   28838     {
   28839       /* Don't treat an argument list as dependent just because it has no
   28840 	 TREE_TYPE.  */
   28841     case TREE_LIST:
   28842     case TREE_VEC:
   28843     case NONTYPE_ARGUMENT_PACK:
   28844       return NULL_TREE;
   28845 
   28846     case TEMPLATE_PARM_INDEX:
   28847       if (dependent_type_p (TREE_TYPE (*tp)))
   28848 	return *tp;
   28849       if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
   28850 	return *tp;
   28851       /* We'll check value-dependence separately.  */
   28852       return NULL_TREE;
   28853 
   28854       /* Handle expressions with type operands.  */
   28855     case SIZEOF_EXPR:
   28856     case ALIGNOF_EXPR:
   28857     case TYPEID_EXPR:
   28858     case AT_ENCODE_EXPR:
   28859       {
   28860 	tree op = TREE_OPERAND (*tp, 0);
   28861 	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
   28862 	  op = TREE_TYPE (op);
   28863 	if (TYPE_P (op))
   28864 	  {
   28865 	    if (dependent_type_p (op))
   28866 	      return *tp;
   28867 	    else
   28868 	      {
   28869 		*walk_subtrees = false;
   28870 		return NULL_TREE;
   28871 	      }
   28872 	  }
   28873 	break;
   28874       }
   28875 
   28876     case COMPONENT_REF:
   28877       if (identifier_p (TREE_OPERAND (*tp, 1)))
   28878 	/* In a template, finish_class_member_access_expr creates a
   28879 	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
   28880 	   type-dependent, so that we can check access control at
   28881 	   instantiation time (PR 42277).  See also Core issue 1273.  */
   28882 	return *tp;
   28883       break;
   28884 
   28885     case SCOPE_REF:
   28886       if (instantiation_dependent_scope_ref_p (*tp))
   28887 	return *tp;
   28888       else
   28889 	break;
   28890 
   28891       /* Treat statement-expressions as dependent.  */
   28892     case BIND_EXPR:
   28893       return *tp;
   28894 
   28895       /* Treat requires-expressions as dependent. */
   28896     case REQUIRES_EXPR:
   28897       return *tp;
   28898 
   28899     case CONSTRUCTOR:
   28900       if (CONSTRUCTOR_IS_DEPENDENT (*tp))
   28901 	return *tp;
   28902       break;
   28903 
   28904     case TEMPLATE_DECL:
   28905     case FUNCTION_DECL:
   28906       /* Before C++17, a noexcept-specifier isn't part of the function type
   28907 	 so it doesn't affect type dependence, but we still want to consider it
   28908 	 for instantiation dependence.  */
   28909       if (cxx_dialect < cxx17
   28910 	  && DECL_DECLARES_FUNCTION_P (*tp)
   28911 	  && value_dependent_noexcept_spec_p (TREE_TYPE (*tp)))
   28912 	return *tp;
   28913       break;
   28914 
   28915     default:
   28916       break;
   28917     }
   28918 
   28919   if (type_dependent_expression_p (*tp))
   28920     return *tp;
   28921   else
   28922     return NULL_TREE;
   28923 }
   28924 
   28925 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
   28926    sense defined by the ABI:
   28927 
   28928    "An expression is instantiation-dependent if it is type-dependent
   28929    or value-dependent, or it has a subexpression that is type-dependent
   28930    or value-dependent."
   28931 
   28932    Except don't actually check value-dependence for unevaluated expressions,
   28933    because in sizeof(i) we don't care about the value of i.  Checking
   28934    type-dependence will in turn check value-dependence of array bounds/template
   28935    arguments as needed.  */
   28936 
   28937 bool
   28938 instantiation_dependent_uneval_expression_p (tree expression)
   28939 {
   28940   tree result;
   28941 
   28942   if (!processing_template_decl)
   28943     return false;
   28944 
   28945   if (expression == error_mark_node)
   28946     return false;
   28947 
   28948   result = cp_walk_tree_without_duplicates (&expression,
   28949 					    instantiation_dependent_r, NULL);
   28950   return result != NULL_TREE;
   28951 }
   28952 
   28953 /* As above, but also check value-dependence of the expression as a whole.  */
   28954 
   28955 bool
   28956 instantiation_dependent_expression_p (tree expression)
   28957 {
   28958   return (instantiation_dependent_uneval_expression_p (expression)
   28959 	  || (processing_template_decl
   28960 	      && potential_constant_expression (expression)
   28961 	      && value_dependent_expression_p (expression)));
   28962 }
   28963 
   28964 /* Like type_dependent_expression_p, but it also works while not processing
   28965    a template definition, i.e. during substitution or mangling.  */
   28966 
   28967 bool
   28968 type_dependent_expression_p_push (tree expr)
   28969 {
   28970   bool b;
   28971   ++processing_template_decl;
   28972   b = type_dependent_expression_p (expr);
   28973   --processing_template_decl;
   28974   return b;
   28975 }
   28976 
   28977 /* Returns TRUE if ARGS contains a type-dependent expression.  */
   28978 
   28979 bool
   28980 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
   28981 {
   28982   if (!processing_template_decl || !args)
   28983     return false;
   28984 
   28985   for (tree arg : *args)
   28986     if (type_dependent_expression_p (arg))
   28987       return true;
   28988 
   28989   return false;
   28990 }
   28991 
   28992 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
   28993    expressions) contains any type-dependent expressions.  */
   28994 
   28995 bool
   28996 any_type_dependent_elements_p (const_tree list)
   28997 {
   28998   for (; list; list = TREE_CHAIN (list))
   28999     if (type_dependent_expression_p (TREE_VALUE (list)))
   29000       return true;
   29001 
   29002   return false;
   29003 }
   29004 
   29005 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
   29006    expressions) contains any value-dependent expressions.  */
   29007 
   29008 bool
   29009 any_value_dependent_elements_p (const_tree list)
   29010 {
   29011   for (; list; list = TREE_CHAIN (list))
   29012     if (value_dependent_expression_p (TREE_VALUE (list)))
   29013       return true;
   29014 
   29015   return false;
   29016 }
   29017 
   29018 /* Returns TRUE if the ARG (a template argument) is dependent.  */
   29019 
   29020 bool
   29021 dependent_template_arg_p (tree arg)
   29022 {
   29023   if (!processing_template_decl)
   29024     return false;
   29025 
   29026   /* Assume a template argument that was wrongly written by the user
   29027      is dependent. This is consistent with what
   29028      any_dependent_template_arguments_p [that calls this function]
   29029      does.  */
   29030   if (!arg || arg == error_mark_node)
   29031     return true;
   29032 
   29033   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
   29034     arg = argument_pack_select_arg (arg);
   29035 
   29036   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
   29037     return true;
   29038   if (TREE_CODE (arg) == TEMPLATE_DECL)
   29039     {
   29040       if (DECL_TEMPLATE_PARM_P (arg))
   29041 	return true;
   29042       /* A member template of a dependent class is not necessarily
   29043 	 type-dependent, but it is a dependent template argument because it
   29044 	 will be a member of an unknown specialization to that template.  */
   29045       tree scope = CP_DECL_CONTEXT (arg);
   29046       return TYPE_P (scope) && dependent_type_p (scope);
   29047     }
   29048   else if (ARGUMENT_PACK_P (arg))
   29049     {
   29050       tree args = ARGUMENT_PACK_ARGS (arg);
   29051       for (tree arg : tree_vec_range (args))
   29052 	if (dependent_template_arg_p (arg))
   29053 	  return true;
   29054       return false;
   29055     }
   29056   else if (TYPE_P (arg))
   29057     return dependent_type_p (arg);
   29058   else
   29059     return value_dependent_expression_p (arg);
   29060 }
   29061 
   29062 /* Identify any expressions that use function parms.  */
   29063 
   29064 static tree
   29065 find_parm_usage_r (tree *tp, int *walk_subtrees, void*)
   29066 {
   29067   tree t = *tp;
   29068   if (TREE_CODE (t) == PARM_DECL)
   29069     {
   29070       *walk_subtrees = 0;
   29071       return t;
   29072     }
   29073   return NULL_TREE;
   29074 }
   29075 
   29076 /* Returns true if a type specialization formed using the template
   29077    arguments ARGS needs to use structural equality.  */
   29078 
   29079 bool
   29080 any_template_arguments_need_structural_equality_p (tree args)
   29081 {
   29082   int i;
   29083   int j;
   29084 
   29085   if (!args)
   29086     return false;
   29087   if (args == error_mark_node)
   29088     return true;
   29089 
   29090   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
   29091     {
   29092       tree level = TMPL_ARGS_LEVEL (args, i + 1);
   29093       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
   29094 	{
   29095 	  tree arg = TREE_VEC_ELT (level, j);
   29096 	  tree packed_args = NULL_TREE;
   29097 	  int k, len = 1;
   29098 
   29099 	  if (ARGUMENT_PACK_P (arg))
   29100 	    {
   29101 	      /* Look inside the argument pack.  */
   29102 	      packed_args = ARGUMENT_PACK_ARGS (arg);
   29103 	      len = TREE_VEC_LENGTH (packed_args);
   29104 	    }
   29105 
   29106 	  for (k = 0; k < len; ++k)
   29107 	    {
   29108 	      if (packed_args)
   29109 		arg = TREE_VEC_ELT (packed_args, k);
   29110 
   29111 	      if (error_operand_p (arg))
   29112 		return true;
   29113 	      else if (TREE_CODE (arg) == TEMPLATE_DECL)
   29114 		continue;
   29115 	      else if (arg == any_targ_node)
   29116 		/* An any_targ_node argument (added by add_defaults_to_ttp)
   29117 		   makes the corresponding specialization not canonicalizable,
   29118 		   since template_args_equal always return true for it.  We
   29119 		   may see this when called from bind_template_template_parm.  */
   29120 		return true;
   29121 	      /* Checking current_function_decl because this structural
   29122 		 comparison is only necessary for redeclaration.  */
   29123 	      else if (!current_function_decl
   29124 		       && dependent_template_arg_p (arg)
   29125 		       && (cp_walk_tree_without_duplicates
   29126 			   (&arg, find_parm_usage_r, NULL)))
   29127 		/* The identity of a class template specialization that uses
   29128 		   a function parameter depends on the identity of the function.
   29129 		   And if this specialization appeared in the trailing return
   29130 		   type thereof, we don't know the identity of the function
   29131 		   (e.g. if it's a redeclaration or a new function) until we
   29132 		   form its signature and go through duplicate_decls.  Thus
   29133 		   it's unsafe to decide on a canonical type now (which depends
   29134 		   on the DECL_CONTEXT of the function parameter, which can get
   29135 		   mutated after the fact by duplicate_decls), so just require
   29136 		   structural equality in this case (PR52830).  */
   29137 		return true;
   29138 	      else if (TYPE_P (arg)
   29139 		       && TYPE_STRUCTURAL_EQUALITY_P (arg)
   29140 		       && dependent_alias_template_spec_p (arg, nt_transparent))
   29141 		/* Require structural equality for specializations written
   29142 		   in terms of a dependent alias template specialization.  */
   29143 		return true;
   29144 	      else if (CLASS_TYPE_P (arg)
   29145 		       && TYPE_TEMPLATE_INFO (arg)
   29146 		       && TYPE_STRUCTURAL_EQUALITY_P (arg))
   29147 		/* Require structural equality for specializations written
   29148 		   in terms of a class template specialization that itself
   29149 		   needs structural equality.  */
   29150 		return true;
   29151 	    }
   29152 	}
   29153     }
   29154 
   29155   return false;
   29156 }
   29157 
   29158 /* Returns true if ARGS (a collection of template arguments) contains
   29159    any dependent arguments.  */
   29160 
   29161 bool
   29162 any_dependent_template_arguments_p (const_tree args)
   29163 {
   29164   if (args == error_mark_node)
   29165     return true;
   29166   if (!processing_template_decl || !args)
   29167     return false;
   29168 
   29169   for (int i = 0, depth = TMPL_ARGS_DEPTH (args); i < depth; ++i)
   29170     {
   29171       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
   29172       for (tree arg : tree_vec_range (CONST_CAST_TREE (level)))
   29173 	if (dependent_template_arg_p (arg))
   29174 	  return true;
   29175     }
   29176 
   29177   return false;
   29178 }
   29179 
   29180 /* Returns true if ARGS contains any errors.  */
   29181 
   29182 bool
   29183 any_erroneous_template_args_p (const_tree args)
   29184 {
   29185   int i;
   29186   int j;
   29187 
   29188   if (args == error_mark_node)
   29189     return true;
   29190 
   29191   if (args && TREE_CODE (args) != TREE_VEC)
   29192     {
   29193       if (tree ti = get_template_info (args))
   29194 	args = TI_ARGS (ti);
   29195       else
   29196 	args = NULL_TREE;
   29197     }
   29198 
   29199   if (!args)
   29200     return false;
   29201 
   29202   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
   29203     {
   29204       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
   29205       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
   29206 	if (error_operand_p (TREE_VEC_ELT (level, j)))
   29207 	  return true;
   29208     }
   29209 
   29210   return false;
   29211 }
   29212 
   29213 /* Returns TRUE if the template TMPL is type-dependent.  */
   29214 
   29215 bool
   29216 dependent_template_p (tree tmpl)
   29217 {
   29218   if (TREE_CODE (tmpl) == OVERLOAD)
   29219     {
   29220       for (lkp_iterator iter (tmpl); iter; ++iter)
   29221 	if (dependent_template_p (*iter))
   29222 	  return true;
   29223       return false;
   29224     }
   29225 
   29226   /* Template template parameters are dependent.  */
   29227   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
   29228       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
   29229     return true;
   29230   /* So are names that have not been looked up.  */
   29231   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
   29232     return true;
   29233   return false;
   29234 }
   29235 
   29236 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
   29237 
   29238 bool
   29239 dependent_template_id_p (tree tmpl, tree args)
   29240 {
   29241   return (dependent_template_p (tmpl)
   29242 	  || any_dependent_template_arguments_p (args));
   29243 }
   29244 
   29245 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
   29246    are dependent.  */
   29247 
   29248 bool
   29249 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
   29250 {
   29251   int i;
   29252 
   29253   if (!processing_template_decl)
   29254     return false;
   29255 
   29256   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
   29257     {
   29258       tree decl = TREE_VEC_ELT (declv, i);
   29259       tree init = TREE_VEC_ELT (initv, i);
   29260       tree cond = TREE_VEC_ELT (condv, i);
   29261       tree incr = TREE_VEC_ELT (incrv, i);
   29262 
   29263       if (type_dependent_expression_p (decl)
   29264 	  || TREE_CODE (decl) == SCOPE_REF)
   29265 	return true;
   29266 
   29267       if (init && type_dependent_expression_p (init))
   29268 	return true;
   29269 
   29270       if (cond == global_namespace)
   29271 	return true;
   29272 
   29273       if (type_dependent_expression_p (cond))
   29274 	return true;
   29275 
   29276       if (COMPARISON_CLASS_P (cond)
   29277 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
   29278 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
   29279 	return true;
   29280 
   29281       if (TREE_CODE (incr) == MODOP_EXPR)
   29282 	{
   29283 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
   29284 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
   29285 	    return true;
   29286 	}
   29287       else if (type_dependent_expression_p (incr))
   29288 	return true;
   29289       else if (TREE_CODE (incr) == MODIFY_EXPR)
   29290 	{
   29291 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
   29292 	    return true;
   29293 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
   29294 	    {
   29295 	      tree t = TREE_OPERAND (incr, 1);
   29296 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
   29297 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
   29298 		return true;
   29299 
   29300 	      /* If this loop has a class iterator with != comparison
   29301 		 with increment other than i++/++i/i--/--i, make sure the
   29302 		 increment is constant.  */
   29303 	      if (CLASS_TYPE_P (TREE_TYPE (decl))
   29304 		  && TREE_CODE (cond) == NE_EXPR)
   29305 		{
   29306 		  if (TREE_OPERAND (t, 0) == decl)
   29307 		    t = TREE_OPERAND (t, 1);
   29308 		  else
   29309 		    t = TREE_OPERAND (t, 0);
   29310 		  if (TREE_CODE (t) != INTEGER_CST)
   29311 		    return true;
   29312 		}
   29313 	    }
   29314 	}
   29315     }
   29316 
   29317   return false;
   29318 }
   29319 
   29320 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
   29321    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
   29322    no such TYPE can be found.  Note that this function peers inside
   29323    uninstantiated templates and therefore should be used only in
   29324    extremely limited situations.  ONLY_CURRENT_P restricts this
   29325    peering to the currently open classes hierarchy (which is required
   29326    when comparing types).  */
   29327 
   29328 tree
   29329 resolve_typename_type (tree type, bool only_current_p)
   29330 {
   29331   tree scope;
   29332   tree name;
   29333   tree decl;
   29334   int quals;
   29335   tree pushed_scope;
   29336   tree result;
   29337 
   29338   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
   29339 
   29340   scope = TYPE_CONTEXT (type);
   29341   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
   29342   gcc_checking_assert (uses_template_parms (scope));
   29343 
   29344   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
   29345      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of a
   29346      TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL
   29347      representing the typedef. In that case TYPE_IDENTIFIER (type) is
   29348      not the non-qualified identifier of the TYPENAME_TYPE anymore.
   29349      So by getting the TYPE_IDENTIFIER of the _main declaration_ of
   29350      the TYPENAME_TYPE instead, we avoid messing up with a possible
   29351      typedef variant case.  */
   29352   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
   29353 
   29354   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
   29355      it first before we can figure out what NAME refers to.  */
   29356   if (TREE_CODE (scope) == TYPENAME_TYPE)
   29357     {
   29358       if (TYPENAME_IS_RESOLVING_P (scope))
   29359 	/* Given a class template A with a dependent base with nested type C,
   29360 	   typedef typename A::C::C C will land us here, as trying to resolve
   29361 	   the initial A::C leads to the local C typedef, which leads back to
   29362 	   A::C::C.  So we break the recursion now.  */
   29363 	return type;
   29364       else
   29365 	scope = resolve_typename_type (scope, only_current_p);
   29366     }
   29367   /* If we don't know what SCOPE refers to, then we cannot resolve the
   29368      TYPENAME_TYPE.  */
   29369   if (!CLASS_TYPE_P (scope))
   29370     return type;
   29371   /* If this is a typedef, we don't want to look inside (c++/11987).  */
   29372   if (typedef_variant_p (type))
   29373     return type;
   29374   /* If SCOPE isn't the template itself, it will not have a valid
   29375      TYPE_FIELDS list.  */
   29376   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
   29377     /* scope is either the template itself or a compatible instantiation
   29378        like X<T>, so look up the name in the original template.  */
   29379     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
   29380   /* If scope has no fields, it can't be a current instantiation.  Check this
   29381      before currently_open_class to avoid infinite recursion (71515).  */
   29382   if (!TYPE_FIELDS (scope))
   29383     return type;
   29384   /* If the SCOPE is not the current instantiation, there's no reason
   29385      to look inside it.  */
   29386   if (only_current_p && !currently_open_class (scope))
   29387     return type;
   29388   /* Enter the SCOPE so that name lookup will be resolved as if we
   29389      were in the class definition.  In particular, SCOPE will no
   29390      longer be considered a dependent type.  */
   29391   pushed_scope = push_scope (scope);
   29392   /* Look up the declaration.  */
   29393   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
   29394 			tf_warning_or_error);
   29395 
   29396   result = NULL_TREE;
   29397 
   29398   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
   29399      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
   29400   tree fullname = TYPENAME_TYPE_FULLNAME (type);
   29401   if (!decl)
   29402     /*nop*/;
   29403   else if (identifier_p (fullname)
   29404 	   && TREE_CODE (decl) == TYPE_DECL)
   29405     {
   29406       result = TREE_TYPE (decl);
   29407       if (result == error_mark_node)
   29408 	result = NULL_TREE;
   29409     }
   29410   else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
   29411 	   && DECL_CLASS_TEMPLATE_P (decl))
   29412     {
   29413       /* Obtain the template and the arguments.  */
   29414       tree tmpl = TREE_OPERAND (fullname, 0);
   29415       if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
   29416 	{
   29417 	  /* We get here with a plain identifier because a previous tentative
   29418 	     parse of the nested-name-specifier as part of a ptr-operator saw
   29419 	     ::template X<A>.  The use of ::template is necessary in a
   29420 	     ptr-operator, but wrong in a declarator-id.
   29421 
   29422 	     [temp.names]: In a qualified-id of a declarator-id, the keyword
   29423 	     template shall not appear at the top level.  */
   29424 	  pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
   29425 		   "keyword %<template%> not allowed in declarator-id");
   29426 	  tmpl = decl;
   29427 	}
   29428       tree args = TREE_OPERAND (fullname, 1);
   29429       /* Instantiate the template.  */
   29430       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
   29431 				      /*entering_scope=*/true,
   29432 				      tf_error | tf_user);
   29433       if (result == error_mark_node)
   29434 	result = NULL_TREE;
   29435     }
   29436 
   29437   /* Leave the SCOPE.  */
   29438   if (pushed_scope)
   29439     pop_scope (pushed_scope);
   29440 
   29441   /* If we failed to resolve it, return the original typename.  */
   29442   if (!result)
   29443     return type;
   29444 
   29445   /* If lookup found a typename type, resolve that too.  */
   29446   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
   29447     {
   29448       /* Ill-formed programs can cause infinite recursion here, so we
   29449 	 must catch that.  */
   29450       TYPENAME_IS_RESOLVING_P (result) = 1;
   29451       result = resolve_typename_type (result, only_current_p);
   29452       TYPENAME_IS_RESOLVING_P (result) = 0;
   29453     }
   29454 
   29455   /* Qualify the resulting type.  */
   29456   quals = cp_type_quals (type);
   29457   if (quals)
   29458     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
   29459 
   29460   return result;
   29461 }
   29462 
   29463 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
   29464    TEMPLATE_TYPE_PARM with a level one deeper than the actual template parms,
   29465    by default.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
   29466 
   29467 static tree
   29468 make_auto_1 (tree name, bool set_canonical, int level = -1)
   29469 {
   29470   if (level == -1)
   29471     level = current_template_depth + 1;
   29472   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
   29473   TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
   29474   TYPE_STUB_DECL (au) = TYPE_NAME (au);
   29475   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
   29476     (0, level, level, TYPE_NAME (au), NULL_TREE);
   29477   if (set_canonical)
   29478     TYPE_CANONICAL (au) = canonical_type_parameter (au);
   29479   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
   29480   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
   29481   if (name == decltype_auto_identifier)
   29482     AUTO_IS_DECLTYPE (au) = true;
   29483 
   29484   return au;
   29485 }
   29486 
   29487 tree
   29488 make_decltype_auto (void)
   29489 {
   29490   return make_auto_1 (decltype_auto_identifier, true);
   29491 }
   29492 
   29493 tree
   29494 make_auto (void)
   29495 {
   29496   return make_auto_1 (auto_identifier, true);
   29497 }
   29498 
   29499 /* Return a C++17 deduction placeholder for class template TMPL.
   29500    There are represented as an 'auto' with the special level 0 and
   29501    CLASS_PLACEHOLDER_TEMPLATE set.  */
   29502 
   29503 tree
   29504 make_template_placeholder (tree tmpl)
   29505 {
   29506   tree t = make_auto_1 (auto_identifier, false, /*level=*/0);
   29507   CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
   29508   /* Our canonical type depends on the placeholder.  */
   29509   TYPE_CANONICAL (t) = canonical_type_parameter (t);
   29510   return t;
   29511 }
   29512 
   29513 /* True iff T is a C++17 class template deduction placeholder.  */
   29514 
   29515 bool
   29516 template_placeholder_p (tree t)
   29517 {
   29518   return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
   29519 }
   29520 
   29521 /* Return an auto for an explicit cast expression auto(x).
   29522    Like CTAD placeholders, these have level 0 so that they're
   29523    not accidentally replaced via tsubst and are always directly
   29524    resolved via do_auto_deduction.  */
   29525 
   29526 tree
   29527 make_cast_auto ()
   29528 {
   29529   return make_auto_1 (auto_identifier, true, /*level=*/0);
   29530 }
   29531 
   29532 /* Make a "constrained auto" type-specifier. This is an auto or
   29533   decltype(auto) type with constraints that must be associated after
   29534   deduction.  The constraint is formed from the given concept CON
   29535   and its optional sequence of template arguments ARGS.
   29536 
   29537   TYPE must be the result of make_auto_type or make_decltype_auto_type. */
   29538 
   29539 static tree
   29540 make_constrained_placeholder_type (tree type, tree con, tree args)
   29541 {
   29542   /* Build the constraint. */
   29543   tree tmpl = DECL_TI_TEMPLATE (con);
   29544   tree expr = tmpl;
   29545   if (TREE_CODE (con) == FUNCTION_DECL)
   29546     expr = ovl_make (tmpl);
   29547   ++processing_template_decl;
   29548   expr = build_concept_check (expr, type, args, tf_warning_or_error);
   29549   --processing_template_decl;
   29550 
   29551   PLACEHOLDER_TYPE_CONSTRAINTS_INFO (type)
   29552     = build_tree_list (current_template_parms, expr);
   29553 
   29554   /* Our canonical type depends on the constraint.  */
   29555   TYPE_CANONICAL (type) = canonical_type_parameter (type);
   29556 
   29557   /* Attach the constraint to the type declaration. */
   29558   return TYPE_NAME (type);
   29559 }
   29560 
   29561 /* Make a "constrained auto" type-specifier.  */
   29562 
   29563 tree
   29564 make_constrained_auto (tree con, tree args)
   29565 {
   29566   tree type = make_auto_1 (auto_identifier, false);
   29567   return make_constrained_placeholder_type (type, con, args);
   29568 }
   29569 
   29570 /* Make a "constrained decltype(auto)" type-specifier.  */
   29571 
   29572 tree
   29573 make_constrained_decltype_auto (tree con, tree args)
   29574 {
   29575   tree type = make_auto_1 (decltype_auto_identifier, false);
   29576   return make_constrained_placeholder_type (type, con, args);
   29577 }
   29578 
   29579 /* Returns true if the placeholder type constraint T has any dependent
   29580    (explicit) template arguments.  */
   29581 
   29582 static bool
   29583 placeholder_type_constraint_dependent_p (tree t)
   29584 {
   29585   tree id = unpack_concept_check (t);
   29586   tree args = TREE_OPERAND (id, 1);
   29587   tree first = TREE_VEC_ELT (args, 0);
   29588   if (ARGUMENT_PACK_P (first))
   29589     {
   29590       args = expand_template_argument_pack (args);
   29591       first = TREE_VEC_ELT (args, 0);
   29592     }
   29593   gcc_checking_assert (TREE_CODE (first) == WILDCARD_DECL
   29594 		       || is_auto (first));
   29595   for (int i = 1; i < TREE_VEC_LENGTH (args); ++i)
   29596     if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
   29597       return true;
   29598   return false;
   29599 }
   29600 
   29601 /* Build and return a concept definition. Like other templates, the
   29602    CONCEPT_DECL node is wrapped by a TEMPLATE_DECL.  This returns the
   29603    the TEMPLATE_DECL. */
   29604 
   29605 tree
   29606 finish_concept_definition (cp_expr id, tree init, tree attrs)
   29607 {
   29608   gcc_assert (identifier_p (id));
   29609   gcc_assert (processing_template_decl);
   29610 
   29611   location_t loc = id.get_location();
   29612 
   29613   /* A concept-definition shall not have associated constraints.  */
   29614   if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
   29615     {
   29616       error_at (loc, "a concept cannot be constrained");
   29617       TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
   29618     }
   29619 
   29620   /* A concept-definition shall appear in namespace scope.  Templates
   29621      aren't allowed in block scope, so we only need to check for class
   29622      scope.  */
   29623   if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
   29624     {
   29625       error_at (loc, "concept %qE not in namespace scope", *id);
   29626       return error_mark_node;
   29627     }
   29628 
   29629   if (current_template_depth > 1)
   29630     {
   29631       error_at (loc, "concept %qE has multiple template parameter lists", *id);
   29632       return error_mark_node;
   29633     }
   29634 
   29635   /* Initially build the concept declaration; its type is bool.  */
   29636   tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
   29637   DECL_CONTEXT (decl) = current_scope ();
   29638   DECL_INITIAL (decl) = init;
   29639 
   29640   if (attrs)
   29641     cplus_decl_attributes (&decl, attrs, 0);
   29642 
   29643   set_originating_module (decl, false);
   29644 
   29645   /* Push the enclosing template.  */
   29646   return push_template_decl (decl);
   29647 }
   29648 
   29649 /* Given type ARG, return std::initializer_list<ARG>.  */
   29650 
   29651 static tree
   29652 listify (tree arg)
   29653 {
   29654   tree std_init_list = lookup_qualified_name (std_node, init_list_identifier);
   29655 
   29656   if (std_init_list == error_mark_node
   29657       || !DECL_CLASS_TEMPLATE_P (std_init_list))
   29658     {
   29659       gcc_rich_location richloc (input_location);
   29660       maybe_add_include_fixit (&richloc, "<initializer_list>", false);
   29661       error_at (&richloc,
   29662 		"deducing from brace-enclosed initializer list"
   29663 		" requires %<#include <initializer_list>%>");
   29664 
   29665       return error_mark_node;
   29666     }
   29667   tree argvec = make_tree_vec (1);
   29668   TREE_VEC_ELT (argvec, 0) = arg;
   29669 
   29670   return lookup_template_class (std_init_list, argvec, NULL_TREE,
   29671 				NULL_TREE, 0, tf_warning_or_error);
   29672 }
   29673 
   29674 /* Replace auto in TYPE with std::initializer_list<auto>.  */
   29675 
   29676 static tree
   29677 listify_autos (tree type, tree auto_node)
   29678 {
   29679   tree init_auto = listify (strip_top_quals (auto_node));
   29680   tree argvec = make_tree_vec (1);
   29681   TREE_VEC_ELT (argvec, 0) = init_auto;
   29682   if (processing_template_decl)
   29683     argvec = add_to_template_args (current_template_args (), argvec);
   29684   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
   29685 }
   29686 
   29687 /* Hash traits for hashing possibly constrained 'auto'
   29688    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
   29689 
   29690 struct auto_hash : default_hash_traits<tree>
   29691 {
   29692   static inline hashval_t hash (tree);
   29693   static inline bool equal (tree, tree);
   29694 };
   29695 
   29696 /* Hash the 'auto' T.  */
   29697 
   29698 inline hashval_t
   29699 auto_hash::hash (tree t)
   29700 {
   29701   if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
   29702     /* Matching constrained-type-specifiers denote the same template
   29703        parameter, so hash the constraint.  */
   29704     return hash_placeholder_constraint (c);
   29705   else
   29706     /* But unconstrained autos are all separate, so just hash the pointer.  */
   29707     return iterative_hash_object (t, 0);
   29708 }
   29709 
   29710 /* Compare two 'auto's.  */
   29711 
   29712 inline bool
   29713 auto_hash::equal (tree t1, tree t2)
   29714 {
   29715   if (t1 == t2)
   29716     return true;
   29717 
   29718   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
   29719   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
   29720 
   29721   /* Two unconstrained autos are distinct.  */
   29722   if (!c1 || !c2)
   29723     return false;
   29724 
   29725   return equivalent_placeholder_constraints (c1, c2);
   29726 }
   29727 
   29728 /* for_each_template_parm callback for extract_autos: if t is a (possibly
   29729    constrained) auto, add it to the vector.  */
   29730 
   29731 static int
   29732 extract_autos_r (tree t, void *data)
   29733 {
   29734   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
   29735   if (is_auto (t) && !template_placeholder_p (t))
   29736     {
   29737       /* All the autos were built with index 0; fix that up now.  */
   29738       tree *p = hash.find_slot (t, INSERT);
   29739       int idx;
   29740       if (*p)
   29741 	/* If this is a repeated constrained-type-specifier, use the index we
   29742 	   chose before.  */
   29743 	idx = TEMPLATE_TYPE_IDX (*p);
   29744       else
   29745 	{
   29746 	  /* Otherwise this is new, so use the current count.  */
   29747 	  *p = t;
   29748 	  idx = hash.elements () - 1;
   29749 	}
   29750       if (idx != TEMPLATE_TYPE_IDX (t))
   29751 	{
   29752 	  gcc_checking_assert (TEMPLATE_TYPE_IDX (t) == 0);
   29753 	  gcc_checking_assert (TYPE_CANONICAL (t) != t);
   29754 	  TEMPLATE_TYPE_IDX (t) = idx;
   29755 	  TYPE_CANONICAL (t) = canonical_type_parameter (t);
   29756 	}
   29757     }
   29758 
   29759   /* Always keep walking.  */
   29760   return 0;
   29761 }
   29762 
   29763 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
   29764    says they can appear anywhere in the type.  */
   29765 
   29766 static tree
   29767 extract_autos (tree type)
   29768 {
   29769   hash_set<tree> visited;
   29770   hash_table<auto_hash> hash (2);
   29771 
   29772   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
   29773 
   29774   tree tree_vec = make_tree_vec (hash.elements());
   29775   for (tree elt : hash)
   29776     {
   29777       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
   29778       TREE_VEC_ELT (tree_vec, i)
   29779 	= build_tree_list (NULL_TREE, TYPE_NAME (elt));
   29780     }
   29781 
   29782   return tree_vec;
   29783 }
   29784 
   29785 /* The stem for deduction guide names.  */
   29786 const char *const dguide_base = "__dguide_";
   29787 
   29788 /* Return the name for a deduction guide for class template TMPL.  */
   29789 
   29790 tree
   29791 dguide_name (tree tmpl)
   29792 {
   29793   tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
   29794   tree tname = TYPE_IDENTIFIER (type);
   29795   char *buf = (char *) alloca (1 + strlen (dguide_base)
   29796 			       + IDENTIFIER_LENGTH (tname));
   29797   memcpy (buf, dguide_base, strlen (dguide_base));
   29798   memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
   29799 	  IDENTIFIER_LENGTH (tname) + 1);
   29800   tree dname = get_identifier (buf);
   29801   TREE_TYPE (dname) = type;
   29802   return dname;
   29803 }
   29804 
   29805 /* True if NAME is the name of a deduction guide.  */
   29806 
   29807 bool
   29808 dguide_name_p (tree name)
   29809 {
   29810   return (TREE_CODE (name) == IDENTIFIER_NODE
   29811 	  && TREE_TYPE (name)
   29812 	  && startswith (IDENTIFIER_POINTER (name), dguide_base));
   29813 }
   29814 
   29815 /* True if FN is a deduction guide.  */
   29816 
   29817 bool
   29818 deduction_guide_p (const_tree fn)
   29819 {
   29820   if (DECL_P (fn))
   29821     if (tree name = DECL_NAME (fn))
   29822       return dguide_name_p (name);
   29823   return false;
   29824 }
   29825 
   29826 /* True if FN is the copy deduction guide, i.e. A(A)->A.  */
   29827 
   29828 bool
   29829 copy_guide_p (const_tree fn)
   29830 {
   29831   gcc_assert (deduction_guide_p (fn));
   29832   if (!DECL_ARTIFICIAL (fn))
   29833     return false;
   29834   tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
   29835   return (TREE_CHAIN (parms) == void_list_node
   29836 	  && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
   29837 }
   29838 
   29839 /* True if FN is a guide generated from a constructor template.  */
   29840 
   29841 bool
   29842 template_guide_p (const_tree fn)
   29843 {
   29844   gcc_assert (deduction_guide_p (fn));
   29845   if (!DECL_ARTIFICIAL (fn))
   29846     return false;
   29847   tree tmpl = DECL_TI_TEMPLATE (fn);
   29848   if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
   29849     return PRIMARY_TEMPLATE_P (org);
   29850   return false;
   29851 }
   29852 
   29853 /* True if FN is an aggregate initialization guide or the copy deduction
   29854    guide.  */
   29855 
   29856 bool
   29857 builtin_guide_p (const_tree fn)
   29858 {
   29859   if (!deduction_guide_p (fn))
   29860     return false;
   29861   if (!DECL_ARTIFICIAL (fn))
   29862     /* Explicitly declared.  */
   29863     return false;
   29864   if (DECL_ABSTRACT_ORIGIN (fn))
   29865     /* Derived from a constructor.  */
   29866     return false;
   29867   return true;
   29868 }
   29869 
   29870 /* True if FN is a C++23 inherited guide.  */
   29871 
   29872 bool
   29873 inherited_guide_p (const_tree fn)
   29874 {
   29875   gcc_assert (deduction_guide_p (fn));
   29876   return LANG_DECL_FN_CHECK (fn)->context != NULL_TREE;
   29877 }
   29878 
   29879 /* Set the base class BASE from which the transformed guide FN
   29880    was inherited as part of C++23 inherited CTAD.  */
   29881 
   29882 static void
   29883 set_inherited_guide_context (const_tree fn, tree base)
   29884 {
   29885   gcc_assert (deduction_guide_p (fn));
   29886   LANG_DECL_FN_CHECK (fn)->context = base;
   29887 }
   29888 
   29889 /* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
   29890    LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
   29891    template parameter types.  Note that the handling of template template
   29892    parameters relies on current_template_parms being set appropriately for the
   29893    new template.  */
   29894 
   29895 static tree
   29896 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
   29897 		       tree tsubst_args, tsubst_flags_t complain)
   29898 {
   29899   if (olddecl == error_mark_node)
   29900     return error_mark_node;
   29901 
   29902   tree oldidx = get_template_parm_index (olddecl);
   29903 
   29904   tree newtype;
   29905   if (TREE_CODE (olddecl) == TYPE_DECL
   29906       || TREE_CODE (olddecl) == TEMPLATE_DECL)
   29907     {
   29908       tree oldtype = TREE_TYPE (olddecl);
   29909       newtype = cxx_make_type (TREE_CODE (oldtype));
   29910       TYPE_MAIN_VARIANT (newtype) = newtype;
   29911     }
   29912   else
   29913     {
   29914       newtype = TREE_TYPE (olddecl);
   29915       if (type_uses_auto (newtype))
   29916 	{
   29917 	  // Substitute once to fix references to other template parameters.
   29918 	  newtype = tsubst (newtype, tsubst_args,
   29919 			    complain|tf_partial, NULL_TREE);
   29920 	  // Now substitute again to reduce the level of the auto.
   29921 	  newtype = tsubst (newtype, current_template_args (),
   29922 			    complain, NULL_TREE);
   29923 	}
   29924       else
   29925 	newtype = tsubst (newtype, tsubst_args,
   29926 			  complain, NULL_TREE);
   29927     }
   29928 
   29929   tree newdecl
   29930     = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
   29931 		  DECL_NAME (olddecl), newtype);
   29932   SET_DECL_TEMPLATE_PARM_P (newdecl);
   29933 
   29934   tree newidx;
   29935   if (TREE_CODE (olddecl) == TYPE_DECL
   29936       || TREE_CODE (olddecl) == TEMPLATE_DECL)
   29937     {
   29938       newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
   29939 	= build_template_parm_index (index, level, level,
   29940 				     newdecl, newtype);
   29941       TEMPLATE_PARM_PARAMETER_PACK (newidx)
   29942 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
   29943       TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
   29944 
   29945       if (TREE_CODE (olddecl) == TEMPLATE_DECL)
   29946 	{
   29947 	  tree newresult
   29948 	    = build_lang_decl_loc (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
   29949 				   DECL_NAME (olddecl), newtype);
   29950 	  DECL_ARTIFICIAL (newresult) = true;
   29951 	  DECL_TEMPLATE_RESULT (newdecl) = newresult;
   29952 	  // First create a copy (ttargs) of tsubst_args with an
   29953 	  // additional level for the template template parameter's own
   29954 	  // template parameters (ttparms).
   29955 	  tree ttparms = (INNERMOST_TEMPLATE_PARMS
   29956 			  (DECL_TEMPLATE_PARMS (olddecl)));
   29957 	  const int depth = TMPL_ARGS_DEPTH (tsubst_args);
   29958 	  tree ttargs = make_tree_vec (depth + 1);
   29959 	  for (int i = 0; i < depth; ++i)
   29960 	    TREE_VEC_ELT (ttargs, i) = TMPL_ARGS_LEVEL (tsubst_args, i + 1);
   29961 	  TREE_VEC_ELT (ttargs, depth)
   29962 	    = template_parms_level_to_args (ttparms);
   29963 	  // Substitute ttargs into ttparms to fix references to
   29964 	  // other template parameters.
   29965 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
   29966 						 complain|tf_partial);
   29967 	  // Now substitute again with args based on tparms, to reduce
   29968 	  // the level of the ttparms.
   29969 	  ttargs = current_template_args ();
   29970 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
   29971 						 complain);
   29972 	  // Finally, tack the adjusted parms onto tparms.
   29973 	  ttparms = tree_cons (size_int (level + 1), ttparms,
   29974 			       copy_node (current_template_parms));
   29975 	  // As with all template template parms, the parameter list captured
   29976 	  // by this template template parm that corresponds to its own level
   29977 	  // should be empty.  This avoids infinite recursion when structurally
   29978 	  // comparing two such rewritten template template parms (PR102479).
   29979 	  gcc_assert (!TREE_VEC_LENGTH
   29980 		      (TREE_VALUE (TREE_CHAIN (DECL_TEMPLATE_PARMS (olddecl)))));
   29981 	  gcc_assert (TMPL_PARMS_DEPTH (TREE_CHAIN (ttparms)) == level);
   29982 	  TREE_VALUE (TREE_CHAIN (ttparms)) = make_tree_vec (0);
   29983 	  // All done.
   29984 	  DECL_TEMPLATE_PARMS (newdecl) = ttparms;
   29985 	  DECL_TEMPLATE_INFO (newresult)
   29986 	    = build_template_info (newdecl, template_parms_to_args (ttparms));
   29987 	}
   29988 
   29989       if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
   29990 	SET_TYPE_STRUCTURAL_EQUALITY (newtype);
   29991       else
   29992 	TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
   29993     }
   29994   else
   29995     {
   29996       tree oldconst = TEMPLATE_PARM_DECL (oldidx);
   29997       tree newconst
   29998 	= build_decl (DECL_SOURCE_LOCATION (oldconst),
   29999 		      TREE_CODE (oldconst),
   30000 		      DECL_NAME (oldconst), newtype);
   30001       TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
   30002 	= TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
   30003       SET_DECL_TEMPLATE_PARM_P (newconst);
   30004       newidx = build_template_parm_index (index, level, level,
   30005 					  newconst, newtype);
   30006       TEMPLATE_PARM_PARAMETER_PACK (newidx)
   30007 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
   30008       DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
   30009     }
   30010 
   30011   return newdecl;
   30012 }
   30013 
   30014 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
   30015    template parameter.  */
   30016 
   30017 static tree
   30018 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
   30019 		    tree targs, unsigned targs_index, tsubst_flags_t complain)
   30020 {
   30021   tree olddecl = TREE_VALUE (oldelt);
   30022   tree newdecl = rewrite_template_parm (olddecl, index, level,
   30023 					targs, complain);
   30024   if (newdecl == error_mark_node)
   30025     return error_mark_node;
   30026   tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
   30027 				     targs, complain, NULL_TREE);
   30028   tree list = build_tree_list (newdef, newdecl);
   30029   TEMPLATE_PARM_CONSTRAINTS (list)
   30030     = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
   30031 			      targs, complain, NULL_TREE);
   30032   int depth = TMPL_ARGS_DEPTH (targs);
   30033   TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
   30034   return list;
   30035 }
   30036 
   30037 /* Returns a C++17 class deduction guide template based on the constructor
   30038    CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
   30039    guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
   30040    aggregate initialization guide.  OUTER_ARGS are the template arguments
   30041    for the enclosing scope of the class.  */
   30042 
   30043 static tree
   30044 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
   30045 {
   30046   tree tparms, targs, fparms, fargs, ci;
   30047   bool memtmpl = false;
   30048   bool explicit_p;
   30049   location_t loc;
   30050   tree fn_tmpl = NULL_TREE;
   30051 
   30052   if (outer_args)
   30053     {
   30054       ++processing_template_decl;
   30055       type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
   30056       --processing_template_decl;
   30057     }
   30058 
   30059   if (!DECL_DECLARES_FUNCTION_P (ctor))
   30060     {
   30061       if (TYPE_P (ctor))
   30062 	{
   30063 	  bool copy_p = TYPE_REF_P (ctor);
   30064 	  if (copy_p)
   30065 	    fparms = tree_cons (NULL_TREE, type, void_list_node);
   30066 	  else
   30067 	    fparms = void_list_node;
   30068 	}
   30069       else if (TREE_CODE (ctor) == TREE_LIST)
   30070 	fparms = ctor;
   30071       else
   30072 	gcc_unreachable ();
   30073 
   30074       tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
   30075       tparms = DECL_TEMPLATE_PARMS (ctmpl);
   30076       targs = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
   30077       ci = NULL_TREE;
   30078       fargs = NULL_TREE;
   30079       loc = DECL_SOURCE_LOCATION (ctmpl);
   30080       explicit_p = false;
   30081     }
   30082   else
   30083     {
   30084       ++processing_template_decl;
   30085       bool ok = true;
   30086 
   30087       complain |= tf_dguide;
   30088 
   30089       fn_tmpl
   30090 	= (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
   30091 	   : DECL_TI_TEMPLATE (ctor));
   30092       if (outer_args)
   30093 	fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
   30094       ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
   30095 
   30096       tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
   30097       /* If type is a member class template, DECL_TI_ARGS (ctor) will have
   30098 	 fully specialized args for the enclosing class.  Strip those off, as
   30099 	 the deduction guide won't have those template parameters.  */
   30100       targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
   30101 						TMPL_PARMS_DEPTH (tparms));
   30102       /* Discard the 'this' parameter.  */
   30103       fparms = FUNCTION_ARG_CHAIN (ctor);
   30104       fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
   30105       ci = get_constraints (ctor);
   30106       loc = DECL_SOURCE_LOCATION (ctor);
   30107       explicit_p = DECL_NONCONVERTING_P (ctor);
   30108 
   30109       if (PRIMARY_TEMPLATE_P (fn_tmpl))
   30110 	{
   30111 	  memtmpl = true;
   30112 
   30113 	  /* For a member template constructor, we need to flatten the two
   30114 	     template parameter lists into one, and then adjust the function
   30115 	     signature accordingly.  This gets...complicated.  */
   30116 	  tree save_parms = current_template_parms;
   30117 
   30118 	  /* For a member template we should have two levels of parms/args, one
   30119 	     for the class and one for the constructor.  We stripped
   30120 	     specialized args for further enclosing classes above.  */
   30121 	  const int depth = 2;
   30122 	  gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
   30123 
   30124 	  /* Template args for translating references to the two-level template
   30125 	     parameters into references to the one-level template parameters we
   30126 	     are creating.  */
   30127 	  tree tsubst_args = copy_node (targs);
   30128 	  TMPL_ARGS_LEVEL (tsubst_args, depth)
   30129 	    = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
   30130 
   30131 	  /* Template parms for the constructor template.  */
   30132 	  tree ftparms = TREE_VALUE (tparms);
   30133 	  unsigned flen = TREE_VEC_LENGTH (ftparms);
   30134 	  /* Template parms for the class template.  */
   30135 	  tparms = TREE_CHAIN (tparms);
   30136 	  tree ctparms = TREE_VALUE (tparms);
   30137 	  unsigned clen = TREE_VEC_LENGTH (ctparms);
   30138 	  /* Template parms for the deduction guide start as a copy of the
   30139 	     template parms for the class.  We set current_template_parms for
   30140 	     lookup_template_class_1.  */
   30141 	  current_template_parms = tparms = copy_node (tparms);
   30142 	  tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
   30143 	  for (unsigned i = 0; i < clen; ++i)
   30144 	    TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
   30145 
   30146 	  /* Now we need to rewrite the constructor parms to append them to the
   30147 	     class parms.  */
   30148 	  for (unsigned i = 0; i < flen; ++i)
   30149 	    {
   30150 	      unsigned index = i + clen;
   30151 	      unsigned level = 1;
   30152 	      tree oldelt = TREE_VEC_ELT (ftparms, i);
   30153 	      tree newelt
   30154 		= rewrite_tparm_list (oldelt, index, level,
   30155 				      tsubst_args, i, complain);
   30156 	      if (newelt == error_mark_node)
   30157 		ok = false;
   30158 	      TREE_VEC_ELT (new_vec, index) = newelt;
   30159 	    }
   30160 
   30161 	  /* Now we have a final set of template parms to substitute into the
   30162 	     function signature.  */
   30163 	  targs = template_parms_to_args (tparms);
   30164 	  fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
   30165 				     complain, ctor);
   30166 	  if (fparms == error_mark_node)
   30167 	    ok = false;
   30168 	  if (ci)
   30169 	    {
   30170 	      if (outer_args)
   30171 		/* FIXME: We'd like to avoid substituting outer template
   30172 		   arguments into the constraint ahead of time, but the
   30173 		   construction of tsubst_args assumes that outer arguments
   30174 		   are already substituted in.  */
   30175 		ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
   30176 	      ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
   30177 	    }
   30178 
   30179 	  /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
   30180 	     cp_unevaluated_operand.  */
   30181 	  cp_evaluated ev;
   30182 	  fargs = tsubst (fargs, tsubst_args, complain, ctor);
   30183 	  current_template_parms = save_parms;
   30184 	}
   30185       else
   30186 	{
   30187 	  /* Substitute in the same arguments to rewrite class members into
   30188 	     references to members of an unknown specialization.  */
   30189 	  cp_evaluated ev;
   30190 	  fparms = tsubst_arg_types (fparms, targs, NULL_TREE, complain, ctor);
   30191 	  fargs = tsubst (fargs, targs, complain, ctor);
   30192 	  if (ci)
   30193 	    {
   30194 	      if (outer_args)
   30195 		/* FIXME: As above.  */
   30196 		ci = tsubst_constraint_info (ci, outer_args, complain, ctor);
   30197 	      ci = tsubst_constraint_info (ci, targs, complain, ctor);
   30198 	    }
   30199 	}
   30200 
   30201       --processing_template_decl;
   30202       if (!ok)
   30203 	return error_mark_node;
   30204     }
   30205 
   30206   if (!memtmpl)
   30207     {
   30208       /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
   30209       tparms = copy_node (tparms);
   30210       INNERMOST_TEMPLATE_PARMS (tparms)
   30211 	= copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
   30212     }
   30213 
   30214   tree fntype = build_function_type (type, fparms);
   30215   tree ded_fn = build_lang_decl_loc (loc,
   30216 				     FUNCTION_DECL,
   30217 				     dguide_name (type), fntype);
   30218   DECL_ARGUMENTS (ded_fn) = fargs;
   30219   DECL_ARTIFICIAL (ded_fn) = true;
   30220   DECL_NONCONVERTING_P (ded_fn) = explicit_p;
   30221   tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
   30222   DECL_ARTIFICIAL (ded_tmpl) = true;
   30223   DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
   30224   DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
   30225   if (DECL_P (ctor))
   30226     DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
   30227   if (ci)
   30228     set_constraints (ded_tmpl, ci);
   30229 
   30230   return ded_tmpl;
   30231 }
   30232 
   30233 /* Add to LIST the member types for the reshaped initializer CTOR.  */
   30234 
   30235 static tree
   30236 collect_ctor_idx_types (tree ctor, tree list, tree elt = NULL_TREE)
   30237 {
   30238   vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
   30239   tree idx, val; unsigned i;
   30240   FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
   30241     {
   30242       tree ftype = elt ? elt : TREE_TYPE (idx);
   30243       if (BRACE_ENCLOSED_INITIALIZER_P (val)
   30244 	  && CONSTRUCTOR_BRACES_ELIDED_P (val))
   30245 	{
   30246 	  tree subelt = NULL_TREE;
   30247 	  if (TREE_CODE (ftype) == ARRAY_TYPE)
   30248 	    subelt = TREE_TYPE (ftype);
   30249 	  list = collect_ctor_idx_types (val, list, subelt);
   30250 	  continue;
   30251 	}
   30252       tree arg = NULL_TREE;
   30253       if (i == v->length() - 1
   30254 	  && PACK_EXPANSION_P (ftype))
   30255 	/* Give the trailing pack expansion parameter a default argument to
   30256 	   match aggregate initialization behavior, even if we deduce the
   30257 	   length of the pack separately to more than we have initializers. */
   30258 	arg = build_constructor (init_list_type_node, NULL);
   30259       /* if ei is of array type and xi is a braced-init-list or string literal,
   30260 	 Ti is an rvalue reference to the declared type of ei */
   30261       STRIP_ANY_LOCATION_WRAPPER (val);
   30262       if (TREE_CODE (ftype) == ARRAY_TYPE
   30263 	  && (BRACE_ENCLOSED_INITIALIZER_P (val)
   30264 	      || TREE_CODE (val) == STRING_CST))
   30265 	{
   30266 	  if (TREE_CODE (val) == STRING_CST)
   30267 	    ftype = cp_build_qualified_type
   30268 	      (ftype, cp_type_quals (ftype) | TYPE_QUAL_CONST);
   30269 	  ftype = (cp_build_reference_type
   30270 		   (ftype, BRACE_ENCLOSED_INITIALIZER_P (val)));
   30271 	}
   30272       list = tree_cons (arg, ftype, list);
   30273     }
   30274 
   30275   return list;
   30276 }
   30277 
   30278 /* Return whether ETYPE is, or is derived from, a specialization of TMPL.  */
   30279 
   30280 static bool
   30281 is_spec_or_derived (tree etype, tree tmpl)
   30282 {
   30283   if (!etype || !CLASS_TYPE_P (etype))
   30284     return false;
   30285 
   30286   etype = cv_unqualified (etype);
   30287   tree type = TREE_TYPE (tmpl);
   30288   tree tparms = (INNERMOST_TEMPLATE_PARMS
   30289 		 (DECL_TEMPLATE_PARMS (tmpl)));
   30290   tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
   30291   int err = unify (tparms, targs, type, etype,
   30292 		   UNIFY_ALLOW_DERIVED, /*explain*/false);
   30293   ggc_free (targs);
   30294   return !err;
   30295 }
   30296 
   30297 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
   30298    INIT.  */
   30299 
   30300 static tree
   30301 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
   30302 {
   30303   if (cxx_dialect < cxx20)
   30304     return NULL_TREE;
   30305 
   30306   if (init == NULL_TREE)
   30307     return NULL_TREE;
   30308 
   30309   if (DECL_ALIAS_TEMPLATE_P (tmpl))
   30310     {
   30311       tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
   30312       tree tinfo = get_template_info (under);
   30313       if (tree guide = maybe_aggr_guide (TI_TEMPLATE (tinfo), init, args))
   30314 	return alias_ctad_tweaks (tmpl, guide);
   30315       return NULL_TREE;
   30316     }
   30317 
   30318   /* We might be creating a guide for a class member template, e.g.,
   30319 
   30320        template<typename U> struct A {
   30321 	 template<typename T> struct B { T t; };
   30322        };
   30323 
   30324      At this point, A will have been instantiated.  Below, we need to
   30325      use both A<U>::B<T> (TEMPLATE_TYPE) and A<int>::B<T> (TYPE) types.  */
   30326   const bool member_template_p
   30327     = (DECL_TEMPLATE_INFO (tmpl)
   30328        && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (tmpl)));
   30329   tree type = TREE_TYPE (tmpl);
   30330   tree template_type = (member_template_p
   30331 			? TREE_TYPE (DECL_TI_TEMPLATE (tmpl))
   30332 			: type);
   30333   if (!CP_AGGREGATE_TYPE_P (template_type))
   30334     return NULL_TREE;
   30335 
   30336   /* No aggregate candidate for copy-initialization.  */
   30337   if (args->length() == 1)
   30338     {
   30339       tree val = (*args)[0];
   30340       if (is_spec_or_derived (TREE_TYPE (val), tmpl))
   30341 	return NULL_TREE;
   30342     }
   30343 
   30344   /* If we encounter a problem, we just won't add the candidate.  */
   30345   tsubst_flags_t complain = tf_none;
   30346 
   30347   tree parms = NULL_TREE;
   30348   if (BRACE_ENCLOSED_INITIALIZER_P (init))
   30349     {
   30350       init = reshape_init (template_type, init, complain);
   30351       if (init == error_mark_node)
   30352 	return NULL_TREE;
   30353       parms = collect_ctor_idx_types (init, parms);
   30354     }
   30355   else if (TREE_CODE (init) == TREE_LIST)
   30356     {
   30357       int len = list_length (init);
   30358       for (tree binfo : BINFO_BASE_BINFOS (TYPE_BINFO (template_type)))
   30359 	{
   30360 	  if (!len)
   30361 	    break;
   30362 	  parms = tree_cons (NULL_TREE, BINFO_TYPE (binfo), parms);
   30363 	  --len;
   30364 	}
   30365       for (tree field = TYPE_FIELDS (template_type);
   30366 	   len;
   30367 	   --len, field = DECL_CHAIN (field))
   30368 	{
   30369 	  field = next_aggregate_field (field);
   30370 	  if (!field)
   30371 	    return NULL_TREE;
   30372 	  tree ftype = finish_decltype_type (field, true, complain);
   30373 	  parms = tree_cons (NULL_TREE, ftype, parms);
   30374 	}
   30375     }
   30376   else
   30377     /* Aggregate initialization doesn't apply to an initializer expression.  */
   30378     return NULL_TREE;
   30379 
   30380   /* If we're creating a deduction guide for a member class template,
   30381      we've used the original template pattern type for the reshape_init
   30382      above; this is done because we want PARMS to be a template parameter
   30383      type, something that can be deduced when used as a function template
   30384      parameter.  At this point the outer class template has already been
   30385      partially instantiated (we deferred the deduction until the enclosing
   30386      scope is non-dependent).  Therefore we have to partially instantiate
   30387      PARMS, so that its template level is properly reduced and we don't get
   30388      mismatches when deducing types using the guide with PARMS.  */
   30389   if (member_template_p)
   30390     {
   30391       ++processing_template_decl;
   30392       parms = tsubst (parms, outer_template_args (tmpl), complain, init);
   30393       --processing_template_decl;
   30394     }
   30395 
   30396   if (parms)
   30397     {
   30398       tree last = parms;
   30399       parms = nreverse (parms);
   30400       TREE_CHAIN (last) = void_list_node;
   30401       tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
   30402       return guide;
   30403     }
   30404 
   30405   return NULL_TREE;
   30406 }
   30407 
   30408 /* UGUIDES are the deduction guides for the underlying template of alias
   30409    template TMPL; adjust them to be deduction guides for TMPL.
   30410 
   30411    This routine also handles C++23 inherited CTAD, in which case TMPL is a
   30412    TREE_LIST representing a synthetic alias template whose TREE_PURPOSE is
   30413    the template parameter list of the alias template (equivalently, of the
   30414    derived class) and TREE_VALUE the defining-type-id (equivalently, the
   30415    base whose guides we're inheriting).  UGUIDES are the base's guides.  */
   30416 
   30417 static tree
   30418 alias_ctad_tweaks (tree tmpl, tree uguides)
   30419 {
   30420   /* [over.match.class.deduct]: When resolving a placeholder for a deduced
   30421      class type (9.2.8.2) where the template-name names an alias template A,
   30422      the defining-type-id of A must be of the form
   30423 
   30424      typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
   30425 
   30426      as specified in 9.2.8.2. The guides of A are the set of functions or
   30427      function templates formed as follows. For each function or function
   30428      template f in the guides of the template named by the simple-template-id
   30429      of the defining-type-id, the template arguments of the return type of f
   30430      are deduced from the defining-type-id of A according to the process in
   30431      13.10.2.5 with the exception that deduction does not fail if not all
   30432      template arguments are deduced. Let g denote the result of substituting
   30433      these deductions into f. If substitution succeeds, form a function or
   30434      function template f' with the following properties and add it to the set
   30435      of guides of A:
   30436 
   30437      * The function type of f' is the function type of g.
   30438 
   30439      * If f is a function template, f' is a function template whose template
   30440      parameter list consists of all the template parameters of A (including
   30441      their default template arguments) that appear in the above deductions or
   30442      (recursively) in their default template arguments, followed by the
   30443      template parameters of f that were not deduced (including their default
   30444      template arguments), otherwise f' is not a function template.
   30445 
   30446      * The associated constraints (13.5.2) are the conjunction of the
   30447      associated constraints of g and a constraint that is satisfied if and only
   30448      if the arguments of A are deducible (see below) from the return type.
   30449 
   30450      * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
   30451      be so as well.
   30452 
   30453      * If f was generated from a deduction-guide (12.4.1.8), then f' is
   30454      considered to be so as well.
   30455 
   30456      * The explicit-specifier of f' is the explicit-specifier of g (if
   30457      any).  */
   30458 
   30459   enum { alias, inherited } ctad_kind;
   30460   tree atype, fullatparms, utype, name;
   30461   if (TREE_CODE (tmpl) == TEMPLATE_DECL)
   30462     {
   30463       ctad_kind = alias;
   30464       atype = TREE_TYPE (tmpl);
   30465       fullatparms = DECL_TEMPLATE_PARMS (tmpl);
   30466       utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
   30467       name = dguide_name (tmpl);
   30468     }
   30469   else
   30470     {
   30471       ctad_kind = inherited;
   30472       atype = NULL_TREE;
   30473       fullatparms = TREE_PURPOSE (tmpl);
   30474       utype = TREE_VALUE (tmpl);
   30475       name = dguide_name (TPARMS_PRIMARY_TEMPLATE
   30476 			  (INNERMOST_TEMPLATE_PARMS (fullatparms)));
   30477     }
   30478 
   30479   tsubst_flags_t complain = tf_none;
   30480   tree aguides = NULL_TREE;
   30481   tree atparms = INNERMOST_TEMPLATE_PARMS (fullatparms);
   30482   unsigned natparms = TREE_VEC_LENGTH (atparms);
   30483   for (tree f : lkp_range (uguides))
   30484     {
   30485       tree in_decl = f;
   30486       location_t loc = DECL_SOURCE_LOCATION (f);
   30487       tree ret = TREE_TYPE (TREE_TYPE (f));
   30488       tree fprime = f;
   30489       if (TREE_CODE (f) == TEMPLATE_DECL)
   30490 	{
   30491 	  processing_template_decl_sentinel ptds (/*reset*/false);
   30492 	  ++processing_template_decl;
   30493 
   30494 	  /* Deduce template arguments for f from the type-id of A.  */
   30495 	  tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
   30496 	  unsigned len = TREE_VEC_LENGTH (ftparms);
   30497 	  tree targs = make_tree_vec (len);
   30498 	  int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
   30499 	  if (err)
   30500 	    /* CWG2664: Discard any deductions, still build the guide.  */
   30501 	    for (unsigned i = 0; i < len; ++i)
   30502 	      TREE_VEC_ELT (targs, i) = NULL_TREE;
   30503 
   30504 	  /* The number of parms for f' is the number of parms of A used in
   30505 	     the deduced arguments plus non-deduced parms of f.  */
   30506 	  unsigned ndlen = 0;
   30507 	  unsigned j;
   30508 	  for (unsigned i = 0; i < len; ++i)
   30509 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
   30510 	      ++ndlen;
   30511 	  find_template_parameter_info ftpi (fullatparms);
   30512 	  ftpi.find_in_recursive (targs);
   30513 	  unsigned nusedatparms = ftpi.num_found ();
   30514 	  unsigned nfparms = nusedatparms + ndlen;
   30515 	  tree gtparms = make_tree_vec (nfparms);
   30516 
   30517 	  /* Set current_template_parms as in build_deduction_guide.  */
   30518 	  auto ctp = make_temp_override (current_template_parms);
   30519 	  current_template_parms = copy_node (fullatparms);
   30520 	  TREE_VALUE (current_template_parms) = gtparms;
   30521 
   30522 	  j = 0;
   30523 	  unsigned level = 1;
   30524 
   30525 	  /* First copy over the used parms of A.  */
   30526 	  tree atargs = make_tree_vec (natparms);
   30527 	  for (unsigned i = 0; i < natparms; ++i)
   30528 	    {
   30529 	      tree elt = TREE_VEC_ELT (atparms, i);
   30530 	      if (ftpi.found (elt))
   30531 		{
   30532 		  unsigned index = j++;
   30533 		  tree nelt = rewrite_tparm_list (elt, index, level,
   30534 						  atargs, i, complain);
   30535 		  TREE_VEC_ELT (gtparms, index) = nelt;
   30536 		}
   30537 	    }
   30538 	  gcc_checking_assert (j == nusedatparms);
   30539 
   30540 	  /* Adjust the deduced template args for f to refer to the A parms
   30541 	     with their new indexes.  */
   30542 	  if (nusedatparms && nusedatparms != natparms)
   30543 	    targs = tsubst_template_args (targs, atargs, complain, in_decl);
   30544 
   30545 	  /* Now rewrite the non-deduced parms of f.  */
   30546 	  for (unsigned i = 0; ndlen && i < len; ++i)
   30547 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
   30548 	      {
   30549 		--ndlen;
   30550 		unsigned index = j++;
   30551 		tree oldlist = TREE_VEC_ELT (ftparms, i);
   30552 		tree list = rewrite_tparm_list (oldlist, index, level,
   30553 						targs, i, complain);
   30554 		TREE_VEC_ELT (gtparms, index) = list;
   30555 	      }
   30556 	  gtparms = build_tree_list (size_one_node, gtparms);
   30557 
   30558 	  /* Substitute the deduced arguments plus the rewritten template
   30559 	     parameters into f to get g.  This covers the type, copyness,
   30560 	     guideness, and explicit-specifier.  */
   30561 	  tree g;
   30562 	    {
   30563 	      /* Parms are to have DECL_CHAIN tsubsted, which would be skipped
   30564 		 if cp_unevaluated_operand.  */
   30565 	      cp_evaluated ev;
   30566 	      g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain,
   30567 			       /*use_spec_table=*/false);
   30568 	    }
   30569 	  if (g == error_mark_node)
   30570 	    continue;
   30571 	  DECL_NAME (g) = name;
   30572 	  if (nfparms == 0)
   30573 	    {
   30574 	      /* The targs are all non-dependent, so g isn't a template.  */
   30575 	      fprime = g;
   30576 	      ret = TREE_TYPE (TREE_TYPE (fprime));
   30577 	      goto non_template;
   30578 	    }
   30579 	  DECL_USE_TEMPLATE (g) = 0;
   30580 	  fprime = build_template_decl (g, gtparms, false);
   30581 	  DECL_TEMPLATE_RESULT (fprime) = g;
   30582 	  TREE_TYPE (fprime) = TREE_TYPE (g);
   30583 	  tree gtargs = template_parms_to_args (gtparms);
   30584 	  DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
   30585 	  DECL_PRIMARY_TEMPLATE (fprime) = fprime;
   30586 
   30587 	  /* Substitute the associated constraints.  */
   30588 	  tree ci = get_constraints (f);
   30589 	  if (ci)
   30590 	    {
   30591 	      if (tree outer_targs = outer_template_args (f))
   30592 		ci = tsubst_constraint_info (ci, outer_targs, complain, in_decl);
   30593 	      ci = tsubst_constraint_info (ci, targs, complain, in_decl);
   30594 	    }
   30595 	  if (ci == error_mark_node)
   30596 	    continue;
   30597 
   30598 	  /* Add a constraint that the return type matches the instantiation of
   30599 	     A with the same template arguments.  */
   30600 	  ret = TREE_TYPE (TREE_TYPE (fprime));
   30601 	  if (ctad_kind == alias
   30602 	      && (!same_type_p (atype, ret)
   30603 		  /* FIXME this should mean they don't compare as equivalent. */
   30604 		  || dependent_alias_template_spec_p (atype, nt_opaque)))
   30605 	    {
   30606 	      tree same = finish_trait_expr (loc, CPTK_IS_DEDUCIBLE, tmpl, ret);
   30607 	      ci = append_constraint (ci, same);
   30608 	    }
   30609 
   30610 	  if (ci)
   30611 	    {
   30612 	      remove_constraints (fprime);
   30613 	      set_constraints (fprime, ci);
   30614 	    }
   30615 	}
   30616       else
   30617 	{
   30618 	  /* For a non-template deduction guide, if the arguments of A aren't
   30619 	     deducible from the return type, don't add the candidate.  */
   30620 	non_template:
   30621 	  if (ctad_kind == alias
   30622 	      && !type_targs_deducible_from (tmpl, ret))
   30623 	    continue;
   30624 	}
   30625 
   30626       /* Rewrite the return type of the inherited guide in terms of the
   30627 	 derived class.  This is specified as replacing the return type R
   30628 	 with typename CC<R>::type where the partially specialized CC maps a
   30629 	 base class specialization to a specialization of the derived class
   30630 	 having such a base (inducing substitution failure if no such derived
   30631 	 class exists).
   30632 
   30633 	 As specified this mapping would be done at instantiation time using
   30634 	 non-dependent template arguments, but we do it ahead of time using
   30635 	 the generic arguments.  This seems to be good enough since generic
   30636 	 deduction should succeed only if concrete deduction would.  */
   30637       if (ctad_kind == inherited)
   30638 	{
   30639 	  processing_template_decl_sentinel ptds (/*reset*/false);
   30640 	  if (TREE_CODE (fprime) == TEMPLATE_DECL)
   30641 	    ++processing_template_decl;
   30642 
   30643 	  tree targs = type_targs_deducible_from (tmpl, ret);
   30644 	  if (!targs)
   30645 	    continue;
   30646 
   30647 	  if (TREE_CODE (f) != TEMPLATE_DECL)
   30648 	    fprime = copy_decl (fprime);
   30649 	  tree fntype = TREE_TYPE (fprime);
   30650 	  ret = lookup_template_class (TPARMS_PRIMARY_TEMPLATE (atparms), targs,
   30651 				       in_decl, NULL_TREE, false, complain);
   30652 	  fntype = build_function_type (ret, TYPE_ARG_TYPES (fntype));
   30653 	  TREE_TYPE (fprime) = fntype;
   30654 	  if (TREE_CODE (fprime) == TEMPLATE_DECL)
   30655 	    TREE_TYPE (DECL_TEMPLATE_RESULT (fprime)) = fntype;
   30656 	  set_inherited_guide_context (fprime, utype);
   30657 	}
   30658 
   30659       aguides = lookup_add (fprime, aguides);
   30660     }
   30661 
   30662   return aguides;
   30663 }
   30664 
   30665 /* CTOR is a using-decl inheriting the constructors of some base of the class
   30666    template TMPL; adjust the base's guides be deduction guides for TMPL.  */
   30667 
   30668 static tree
   30669 inherited_ctad_tweaks (tree tmpl, tree ctor, tsubst_flags_t complain)
   30670 {
   30671   /* [over.match.class.deduct]: In addition, if C is defined and inherits
   30672      constructors ([namespace.udecl]) from a direct base class denoted in the
   30673      base-specifier-list by a class-or-decltype B, let A be an alias template
   30674      whose template parameter list is that of C and whose defining-type-id is
   30675      B.  If A is a deducible template ([dcl.type.simple]), the set contains the
   30676      guides of A with the return type R of each guide replaced with typename
   30677      CC::type given a class template
   30678 
   30679      template <typename> class CC;
   30680 
   30681      whose primary template is not defined and with a single partial
   30682      specialization whose template parameter list is that of A and whose
   30683      template argument list is a specialization of A with the template argument
   30684      list of A ([temp.dep.type]) having a member typedef type designating a
   30685      template specialization with the template argument list of A but with C as
   30686      the template.  */
   30687 
   30688   tree scope = USING_DECL_SCOPE (ctor);
   30689   if (TREE_CODE (scope) == TYPENAME_TYPE
   30690       && (TYPE_IDENTIFIER (TYPE_CONTEXT (scope))
   30691 	  == TYPENAME_TYPE_FULLNAME (scope)))
   30692     /* Recognize using B<T>::B::B as an inherited constructor.  */
   30693     /* FIXME: Also recognize using C::B::B?  We might have to call
   30694        resolve_typename_type for that.  */
   30695     scope = TYPE_CONTEXT (scope);
   30696   if (!CLASS_TYPE_P (scope)
   30697       || !CLASSTYPE_TEMPLATE_INFO (scope)
   30698       || !PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (scope)))
   30699     return NULL_TREE;
   30700 
   30701   tree t = build_tree_list (DECL_TEMPLATE_PARMS (tmpl), scope);
   30702   bool any_dguides_p;
   30703   tree uguides = deduction_guides_for (CLASSTYPE_TI_TEMPLATE (scope),
   30704 				       any_dguides_p, complain);
   30705   return alias_ctad_tweaks (t, uguides);
   30706 }
   30707 
   30708 /* If template arguments for TMPL can be deduced from TYPE, return
   30709    the deduced arguments, otherwise return NULL_TREE.
   30710    Used to implement CPTK_IS_DEDUCIBLE for alias CTAD according to
   30711    [over.match.class.deduct].
   30712 
   30713    This check is specified in terms of partial specialization, so the behavior
   30714    should be parallel to that of get_partial_spec_bindings.  */
   30715 
   30716 tree
   30717 type_targs_deducible_from (tree tmpl, tree type)
   30718 {
   30719   tree tparms, ttype;
   30720   if (TREE_CODE (tmpl) == TEMPLATE_DECL)
   30721     {
   30722       /* If tmpl is a class template, this is trivial: it's deducible if
   30723 	 TYPE is a specialization of TMPL.  */
   30724       if (DECL_CLASS_TEMPLATE_P (tmpl))
   30725 	{
   30726 	  if (CLASS_TYPE_P (type)
   30727 	      && CLASSTYPE_TEMPLATE_INFO (type)
   30728 	      && CLASSTYPE_TI_TEMPLATE (type) == tmpl)
   30729 	    return INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
   30730 	  else
   30731 	    return NULL_TREE;
   30732 	}
   30733 
   30734       /* Otherwise it's an alias template.  */
   30735       tparms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
   30736       ttype = TREE_TYPE (tmpl);
   30737     }
   30738   else
   30739     {
   30740       /* TMPL is a synthetic alias template represented as a TREE_LIST as
   30741 	 per alias_ctad_tweaks.  */
   30742       tparms = INNERMOST_TEMPLATE_PARMS (TREE_PURPOSE (tmpl));
   30743       ttype = TREE_VALUE (tmpl);
   30744       tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (ttype);
   30745       if (!ti)
   30746 	/* TTYPE is a typedef to a template-id.  */
   30747 	ti = TYPE_TEMPLATE_INFO (ttype);
   30748       tmpl = TI_TEMPLATE (ti);
   30749     }
   30750 
   30751   int len = TREE_VEC_LENGTH (tparms);
   30752   tree targs = make_tree_vec (len);
   30753   bool tried_array_deduction = (cxx_dialect < cxx17);
   30754 
   30755  again:
   30756   if (unify (tparms, targs, ttype, type,
   30757 	     UNIFY_ALLOW_NONE, false))
   30758     return NULL_TREE;
   30759 
   30760   /* We don't fail on an undeduced targ the second time through (like
   30761      get_partial_spec_bindings) because we're going to try defaults.  */
   30762   for (int i =  0; i < len; ++i)
   30763     if (! TREE_VEC_ELT (targs, i))
   30764       {
   30765 	tree tparm = TREE_VEC_ELT (tparms, i);
   30766 	tparm = TREE_VALUE (tparm);
   30767 
   30768 	if (!tried_array_deduction
   30769 	    && TREE_CODE (tparm) == TYPE_DECL)
   30770 	  {
   30771 	    try_array_deduction (tparms, targs, ttype);
   30772 	    tried_array_deduction = true;
   30773 	    if (TREE_VEC_ELT (targs, i))
   30774 	      goto again;
   30775 	  }
   30776 	/* If the type parameter is a parameter pack, then it will be deduced
   30777 	   to an empty parameter pack.  This is another case that doesn't model
   30778 	   well as partial specialization.  */
   30779 	if (template_parameter_pack_p (tparm))
   30780 	  {
   30781 	    tree arg;
   30782 	    if (TREE_CODE (tparm) == PARM_DECL)
   30783 	      {
   30784 		arg = make_node (NONTYPE_ARGUMENT_PACK);
   30785 		TREE_CONSTANT (arg) = 1;
   30786 	      }
   30787 	    else
   30788 	      arg = cxx_make_type (TYPE_ARGUMENT_PACK);
   30789 	    ARGUMENT_PACK_ARGS (arg) = make_tree_vec (0);
   30790 	    TREE_VEC_ELT (targs, i) = arg;
   30791 	  }
   30792       }
   30793 
   30794   /* Maybe add in default template args.  This seems like a flaw in the
   30795      specification in terms of partial specialization, since it says the
   30796      partial specialization has the template parameter list of A, but a
   30797      partial specialization can't have default targs.  */
   30798   targs = coerce_template_parms (tparms, targs, tmpl, tf_none);
   30799   if (targs == error_mark_node)
   30800     return NULL_TREE;
   30801 
   30802   /* I believe we don't need the template_template_parm_bindings_ok_p call
   30803      because coerce_template_parms did coerce_template_template_parms.  */
   30804 
   30805   if (!constraints_satisfied_p (tmpl, targs))
   30806     return NULL_TREE;
   30807 
   30808   return targs;
   30809 }
   30810 
   30811 /* Return artificial deduction guides built from the constructors of class
   30812    template TMPL.  */
   30813 
   30814 static tree
   30815 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
   30816 {
   30817   tree outer_args = outer_template_args (tmpl);
   30818   tree type = TREE_TYPE (most_general_template (tmpl));
   30819 
   30820   tree cands = NULL_TREE;
   30821 
   30822   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
   30823     {
   30824       /* We handle C++23 inherited CTAD below.  */
   30825       if (iter.using_p ())
   30826 	continue;
   30827 
   30828       tree guide = build_deduction_guide (type, *iter, outer_args, complain);
   30829       cands = lookup_add (guide, cands);
   30830     }
   30831 
   30832   if (cxx_dialect >= cxx23)
   30833     /* FIXME: CLASSTYPE_CONSTRUCTORS doesn't contain inherited constructors if
   30834        e.g. the class also has a user-defined constructor.  So instead iterate
   30835        over TYPE_FIELDS manually to robustly find all relevant using-decls.  */
   30836     for (tree field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
   30837       if (TREE_CODE (field) == USING_DECL
   30838 	  && DECL_NAME (field) == ctor_identifier)
   30839 	{
   30840 	  tree uguides = inherited_ctad_tweaks (tmpl, field, complain);
   30841 	  if (uguides)
   30842 	    cands = lookup_add (uguides, cands);
   30843 	}
   30844 
   30845   /* Add implicit default constructor deduction guide.  */
   30846   if (!TYPE_HAS_USER_CONSTRUCTOR (type))
   30847     {
   30848       tree guide = build_deduction_guide (type, type, outer_args,
   30849 					  complain);
   30850       cands = lookup_add (guide, cands);
   30851     }
   30852 
   30853   /* Add copy guide.  */
   30854   {
   30855     tree gtype = build_reference_type (type);
   30856     tree guide = build_deduction_guide (type, gtype, outer_args,
   30857 					complain);
   30858     cands = lookup_add (guide, cands);
   30859   }
   30860 
   30861   return cands;
   30862 }
   30863 
   30864 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
   30865 
   30866 /* Return the non-aggregate deduction guides for deducible template TMPL.  The
   30867    aggregate candidate is added separately because it depends on the
   30868    initializer.  Set ANY_DGUIDES_P if we find a non-implicit deduction
   30869    guide.  */
   30870 
   30871 static tree
   30872 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
   30873 {
   30874   tree guides = NULL_TREE;
   30875   if (DECL_ALIAS_TEMPLATE_P (tmpl))
   30876     {
   30877       tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
   30878       tree tinfo = get_template_info (under);
   30879       guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
   30880 				     complain);
   30881     }
   30882   else
   30883     {
   30884       guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
   30885 				      dguide_name (tmpl),
   30886 				      LOOK_want::NORMAL, /*complain*/false);
   30887       if (guides == error_mark_node)
   30888 	guides = NULL_TREE;
   30889       else
   30890 	any_dguides_p = true;
   30891     }
   30892 
   30893   /* Cache the deduction guides for a template.  We also remember the result of
   30894      lookup, and rebuild everything if it changes; should be very rare.  */
   30895   /* FIXME: Also rebuild if this is a class template that inherits guides from a
   30896      base class, and lookup for the latter changed.  */
   30897   tree_pair_p cache = NULL;
   30898   if (tree_pair_p &r
   30899       = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
   30900     {
   30901       cache = r;
   30902       if (cache->purpose == guides)
   30903 	return cache->value;
   30904     }
   30905   else
   30906     {
   30907       r = cache = ggc_cleared_alloc<tree_pair_s> ();
   30908       cache->purpose = guides;
   30909     }
   30910 
   30911   tree cands = NULL_TREE;
   30912   if (DECL_ALIAS_TEMPLATE_P (tmpl))
   30913     cands = alias_ctad_tweaks (tmpl, guides);
   30914   else
   30915     {
   30916       cands = ctor_deduction_guides_for (tmpl, complain);
   30917       for (ovl_iterator it (guides); it; ++it)
   30918 	cands = lookup_add (*it, cands);
   30919     }
   30920 
   30921   cache->value = cands;
   30922   return cands;
   30923 }
   30924 
   30925 /* Return whether TMPL is a (class template argument-) deducible template.  */
   30926 
   30927 bool
   30928 ctad_template_p (tree tmpl)
   30929 {
   30930   /* A deducible template is either a class template or is an alias template
   30931      whose defining-type-id is of the form
   30932 
   30933       typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
   30934 
   30935      where the nested-name-specifier (if any) is non-dependent and the
   30936      template-name of the simple-template-id names a deducible template.  */
   30937 
   30938   if (DECL_CLASS_TEMPLATE_P (tmpl)
   30939       || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
   30940     return true;
   30941   if (!DECL_ALIAS_TEMPLATE_P (tmpl))
   30942     return false;
   30943   tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
   30944   if (tree tinfo = get_template_info (orig))
   30945     return ctad_template_p (TI_TEMPLATE (tinfo));
   30946   return false;
   30947 }
   30948 
   30949 /* Deduce template arguments for the class template placeholder PTYPE for
   30950    template TMPL based on the initializer INIT, and return the resulting
   30951    type.  */
   30952 
   30953 static tree
   30954 do_class_deduction (tree ptype, tree tmpl, tree init, tree outer_targs,
   30955 		    int flags, tsubst_flags_t complain)
   30956 {
   30957   /* We should have handled this in the caller.  */
   30958   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
   30959     return ptype;
   30960 
   30961   /* If the class was erroneous, don't try to deduce, because that
   30962      can generate a lot of diagnostic.  */
   30963   if (TREE_TYPE (tmpl)
   30964       && TYPE_LANG_SPECIFIC (TREE_TYPE (tmpl))
   30965       && CLASSTYPE_ERRONEOUS (TREE_TYPE (tmpl)))
   30966     return ptype;
   30967 
   30968   /* Wait until the enclosing scope is non-dependent.  */
   30969   if (DECL_CLASS_SCOPE_P (tmpl)
   30970       && dependent_type_p (DECL_CONTEXT (tmpl)))
   30971     return ptype;
   30972 
   30973   /* Initializing one placeholder from another.  */
   30974   if (init
   30975       && (TREE_CODE (init) == TEMPLATE_PARM_INDEX
   30976 	  || (TREE_CODE (init) == EXPR_PACK_EXPANSION
   30977 	      && (TREE_CODE (PACK_EXPANSION_PATTERN (init))
   30978 		  == TEMPLATE_PARM_INDEX)))
   30979       && is_auto (TREE_TYPE (init))
   30980       && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
   30981     return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
   30982 
   30983   if (!ctad_template_p (tmpl))
   30984     {
   30985       if (complain & tf_error)
   30986 	error ("non-deducible template %qT used without template arguments", tmpl);
   30987       return error_mark_node;
   30988     }
   30989   else if (cxx_dialect < cxx20 && DECL_ALIAS_TEMPLATE_P (tmpl))
   30990     {
   30991       if (complain & tf_error)
   30992 	{
   30993 	  /* Be permissive with equivalent alias templates.  */
   30994 	  tree u = get_underlying_template (tmpl);
   30995 	  diagnostic_t dk = (u == tmpl) ? DK_ERROR : DK_PEDWARN;
   30996 	  bool complained
   30997 	    = emit_diagnostic (dk, input_location, 0,
   30998 			       "alias template deduction only available "
   30999 			       "with %<-std=c++20%> or %<-std=gnu++20%>");
   31000 	  if (u == tmpl)
   31001 	    return error_mark_node;
   31002 	  else if (complained)
   31003 	    {
   31004 	      inform (input_location, "use %qD directly instead", u);
   31005 	      tmpl = u;
   31006 	    }
   31007 	}
   31008       else
   31009 	return error_mark_node;
   31010     }
   31011 
   31012   /* Wait until the initializer is non-dependent.  */
   31013   if (type_dependent_expression_p (init))
   31014     return ptype;
   31015 
   31016   if (outer_targs)
   31017     {
   31018       int args_depth = TMPL_ARGS_DEPTH (outer_targs);
   31019       int parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
   31020       if (parms_depth > 1)
   31021 	{
   31022 	  /* Substitute outer arguments into this CTAD template from the
   31023 	     current instantiation.  */
   31024 	  int want = std::min (args_depth, parms_depth - 1);
   31025 	  outer_targs = strip_innermost_template_args (outer_targs,
   31026 						       args_depth - want);
   31027 	  tmpl = tsubst (tmpl, outer_targs, complain, NULL_TREE);
   31028 	  if (tmpl == error_mark_node)
   31029 	    return error_mark_node;
   31030 	}
   31031     }
   31032 
   31033   /* Don't bother with the alias rules for an equivalent template.  */
   31034   tmpl = get_underlying_template (tmpl);
   31035 
   31036   tree type = TREE_TYPE (tmpl);
   31037 
   31038   bool try_list_cand = false;
   31039   bool list_init_p = false;
   31040 
   31041   releasing_vec rv_args = NULL;
   31042   vec<tree,va_gc> *&args = *&rv_args;
   31043   if (init == NULL_TREE)
   31044     args = make_tree_vector ();
   31045   else if (BRACE_ENCLOSED_INITIALIZER_P (init))
   31046     {
   31047       list_init_p = true;
   31048       try_list_cand = true;
   31049       if (CONSTRUCTOR_NELTS (init) == 1
   31050 	  && !CONSTRUCTOR_IS_DESIGNATED_INIT (init))
   31051 	{
   31052 	  /* As an exception, the first phase in 16.3.1.7 (considering the
   31053 	     initializer list as a single argument) is omitted if the
   31054 	     initializer list consists of a single expression of type cv U,
   31055 	     where U is a specialization of C or a class derived from a
   31056 	     specialization of C.  */
   31057 	  tree elt = CONSTRUCTOR_ELT (init, 0)->value;
   31058 	  if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
   31059 	    try_list_cand = false;
   31060 	}
   31061       if (try_list_cand || is_std_init_list (type))
   31062 	args = make_tree_vector_single (init);
   31063       else
   31064 	args = make_tree_vector_from_ctor (init);
   31065     }
   31066   else if (TREE_CODE (init) == TREE_LIST)
   31067     args = make_tree_vector_from_list (init);
   31068   else
   31069     args = make_tree_vector_single (init);
   31070 
   31071   /* Do this now to avoid problems with erroneous args later on.  */
   31072   args = resolve_args (args, complain);
   31073   if (args == NULL)
   31074     return error_mark_node;
   31075 
   31076   bool any_dguides_p = false;
   31077   tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
   31078   if (cands == error_mark_node)
   31079     return error_mark_node;
   31080 
   31081   /* Prune explicit deduction guides in copy-initialization context (but
   31082      not copy-list-initialization).  */
   31083   bool elided = false;
   31084   if (!list_init_p && (flags & LOOKUP_ONLYCONVERTING))
   31085     {
   31086       for (lkp_iterator iter (cands); !elided && iter; ++iter)
   31087 	if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
   31088 	  elided = true;
   31089 
   31090       if (elided)
   31091 	{
   31092 	  /* Found a nonconverting guide, prune the candidates.  */
   31093 	  tree pruned = NULL_TREE;
   31094 	  for (lkp_iterator iter (cands); iter; ++iter)
   31095 	    if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
   31096 	      pruned = lookup_add (*iter, pruned);
   31097 
   31098 	  cands = pruned;
   31099 	}
   31100     }
   31101 
   31102   if (!any_dguides_p)
   31103     if (tree guide = maybe_aggr_guide (tmpl, init, args))
   31104       cands = lookup_add (guide, cands);
   31105 
   31106   tree fndecl = error_mark_node;
   31107 
   31108   /* If this is list-initialization and the class has a list guide, first
   31109      try deducing from the list as a single argument, as [over.match.list].  */
   31110   if (try_list_cand)
   31111     {
   31112       tree list_cands = NULL_TREE;
   31113       for (tree dg : lkp_range (cands))
   31114 	if (is_list_ctor (dg))
   31115 	  list_cands = lookup_add (dg, list_cands);
   31116       if (list_cands)
   31117 	fndecl = perform_dguide_overload_resolution (list_cands, args, tf_none);
   31118       if (fndecl == error_mark_node)
   31119 	{
   31120 	  /* That didn't work, now try treating the list as a sequence of
   31121 	     arguments.  */
   31122 	  release_tree_vector (args);
   31123 	  args = make_tree_vector_from_ctor (init);
   31124 	  args = resolve_args (args, complain);
   31125 	  if (args == NULL)
   31126 	    return error_mark_node;
   31127 	}
   31128     }
   31129 
   31130   if (elided && !cands)
   31131     {
   31132       error ("cannot deduce template arguments for copy-initialization"
   31133 	     " of %qT, as it has no non-explicit deduction guides or "
   31134 	     "user-declared constructors", type);
   31135       return error_mark_node;
   31136     }
   31137   else if (!cands && fndecl == error_mark_node)
   31138     {
   31139       error ("cannot deduce template arguments of %qT, as it has no viable "
   31140 	     "deduction guides", type);
   31141       return error_mark_node;
   31142     }
   31143 
   31144   if (fndecl == error_mark_node)
   31145     fndecl = perform_dguide_overload_resolution (cands, args, tf_none);
   31146 
   31147   if (fndecl == error_mark_node)
   31148     {
   31149       if (complain & tf_warning_or_error)
   31150 	{
   31151 	  error ("class template argument deduction failed:");
   31152 	  perform_dguide_overload_resolution (cands, args, complain);
   31153 	  if (elided)
   31154 	    inform (input_location, "explicit deduction guides not considered "
   31155 		    "for copy-initialization");
   31156 	}
   31157       return error_mark_node;
   31158     }
   31159   /* [over.match.list]/1: In copy-list-initialization, if an explicit
   31160      constructor is chosen, the initialization is ill-formed.  */
   31161   else if (flags & LOOKUP_ONLYCONVERTING)
   31162     {
   31163       if (DECL_NONCONVERTING_P (fndecl))
   31164 	{
   31165 	  if (complain & tf_warning_or_error)
   31166 	    {
   31167 	      // TODO: Pass down location from cp_finish_decl.
   31168 	      error ("class template argument deduction for %qT failed: "
   31169 		     "explicit deduction guide selected in "
   31170 		     "copy-list-initialization", type);
   31171 	      inform (DECL_SOURCE_LOCATION (fndecl),
   31172 		      "explicit deduction guide declared here");
   31173 
   31174 	    }
   31175 	  return error_mark_node;
   31176 	}
   31177     }
   31178 
   31179   /* If CTAD succeeded but the type doesn't have any explicit deduction
   31180      guides, this deduction might not be what the user intended.  */
   31181   if (fndecl != error_mark_node && !any_dguides_p && (complain & tf_warning))
   31182     {
   31183       if ((!DECL_IN_SYSTEM_HEADER (fndecl)
   31184 	   || global_dc->m_warn_system_headers)
   31185 	  && warning (OPT_Wctad_maybe_unsupported,
   31186 		      "%qT may not intend to support class template argument "
   31187 		      "deduction", type))
   31188 	inform (input_location, "add a deduction guide to suppress this "
   31189 		"warning");
   31190     }
   31191 
   31192   return cp_build_qualified_type (TREE_TYPE (TREE_TYPE (fndecl)),
   31193 				  cp_type_quals (ptype));
   31194 }
   31195 
   31196 /* Return true if INIT is an unparenthesized id-expression or an
   31197    unparenthesized class member access.  Used for the argument of
   31198    decltype(auto).  */
   31199 
   31200 bool
   31201 unparenthesized_id_or_class_member_access_p (tree init)
   31202 {
   31203   STRIP_ANY_LOCATION_WRAPPER (init);
   31204 
   31205   /* We need to be able to tell '(r)' and 'r' apart (when it's of
   31206      reference type).  Only the latter is an id-expression.  */
   31207   if (REFERENCE_REF_P (init)
   31208       && !REF_PARENTHESIZED_P (init))
   31209     init = TREE_OPERAND (init, 0);
   31210   return (DECL_P (init)
   31211 	  || ((TREE_CODE (init) == COMPONENT_REF
   31212 	       || TREE_CODE (init) == SCOPE_REF)
   31213 	      && !REF_PARENTHESIZED_P (init)));
   31214 }
   31215 
   31216 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
   31217    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
   31218    The CONTEXT determines the context in which auto deduction is performed
   31219    and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
   31220 
   31221    OUTER_TARGS is used during template argument deduction (context == adc_unify)
   31222    to properly substitute the result.  It's also used in the adc_unify and
   31223    adc_requirement contexts to communicate the necessary template arguments
   31224    to satisfaction.  OUTER_TARGS is ignored in other contexts.
   31225 
   31226    Additionally for adc_unify contexts TMPL is the template for which TYPE
   31227    is a template parameter type.
   31228 
   31229    For partial-concept-ids, extra args from OUTER_TARGS, TMPL and the current
   31230    scope may be appended to the list of deduced template arguments prior to
   31231    determining constraint satisfaction as appropriate.  */
   31232 
   31233 tree
   31234 do_auto_deduction (tree type, tree init, tree auto_node,
   31235 		   tsubst_flags_t complain /* = tf_warning_or_error */,
   31236 		   auto_deduction_context context /* = adc_unspecified */,
   31237 		   tree outer_targs /* = NULL_TREE */,
   31238 		   int flags /* = LOOKUP_NORMAL */,
   31239 		   tree tmpl /* = NULL_TREE */)
   31240 {
   31241   if (type == error_mark_node || init == error_mark_node)
   31242     return error_mark_node;
   31243 
   31244   if (init && type_dependent_expression_p (init)
   31245       && context != adc_unify)
   31246     /* Defining a subset of type-dependent expressions that we can deduce
   31247        from ahead of time isn't worth the trouble.  */
   31248     return type;
   31249 
   31250   /* Similarly, we can't deduce from another undeduced decl.  */
   31251   if (init && undeduced_auto_decl (init))
   31252     return type;
   31253 
   31254   /* We may be doing a partial substitution, but we still want to replace
   31255      auto_node.  */
   31256   complain &= ~tf_partial;
   31257 
   31258   if (init && BRACE_ENCLOSED_INITIALIZER_P (init))
   31259     {
   31260       /* We don't recurse here because we can't deduce from a nested
   31261 	 initializer_list.  */
   31262       if (CONSTRUCTOR_ELTS (init))
   31263 	for (constructor_elt &elt : CONSTRUCTOR_ELTS (init))
   31264 	  elt.value = resolve_nondeduced_context (elt.value, complain);
   31265     }
   31266   else if (init)
   31267     init = resolve_nondeduced_context (init, complain);
   31268 
   31269   /* In C++23, we must deduce the type to int&& for code like
   31270        decltype(auto) f(int&& x) { return (x); }
   31271      or
   31272        auto&& f(int x) { return x; }
   31273      so we use treat_lvalue_as_rvalue_p.  But don't do it for
   31274        decltype(auto) f(int x) { return x; }
   31275      where we should deduce 'int' rather than 'int&&'; transmogrifying
   31276      INIT to an rvalue would break that.  */
   31277   tree r;
   31278   if (cxx_dialect >= cxx23
   31279       && context == adc_return_type
   31280       && (!AUTO_IS_DECLTYPE (auto_node)
   31281 	  || !unparenthesized_id_or_class_member_access_p (init))
   31282       && (r = treat_lvalue_as_rvalue_p (maybe_undo_parenthesized_ref (init),
   31283 					/*return*/true)))
   31284     init = r;
   31285 
   31286   if (tree ctmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
   31287     /* C++17 class template argument deduction.  */
   31288     return do_class_deduction (type, ctmpl, init, outer_targs, flags, complain);
   31289 
   31290   if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
   31291     /* Nothing we can do with this, even in deduction context.  */
   31292     return type;
   31293 
   31294   location_t loc = cp_expr_loc_or_input_loc (init);
   31295 
   31296   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
   31297      with either a new invented type template parameter U or, if the
   31298      initializer is a braced-init-list (8.5.4), with
   31299      std::initializer_list<U>.  */
   31300   if (BRACE_ENCLOSED_INITIALIZER_P (init))
   31301     {
   31302       if (!DIRECT_LIST_INIT_P (init))
   31303 	type = listify_autos (type, auto_node);
   31304       else if (CONSTRUCTOR_NELTS (init) == 1)
   31305 	init = CONSTRUCTOR_ELT (init, 0)->value;
   31306       else
   31307 	{
   31308           if (complain & tf_warning_or_error)
   31309             {
   31310 	      if (permerror (loc, "direct-list-initialization of "
   31311 			     "%<auto%> requires exactly one element"))
   31312 		inform (loc,
   31313 		        "for deduction to %<std::initializer_list%>, use copy-"
   31314 		        "list-initialization (i.e. add %<=%> before the %<{%>)");
   31315             }
   31316 	  type = listify_autos (type, auto_node);
   31317 	}
   31318     }
   31319 
   31320   if (type == error_mark_node || init == error_mark_node)
   31321     return error_mark_node;
   31322 
   31323   tree targs;
   31324   if (context == adc_decomp_type
   31325       && auto_node == type
   31326       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
   31327     {
   31328       /* [dcl.struct.bind]/1 - if decomposition declaration has no ref-qualifiers
   31329 	 and initializer has array type, deduce cv-qualified array type.  */
   31330       targs = make_tree_vec (1);
   31331       TREE_VEC_ELT (targs, 0) = TREE_TYPE (init);
   31332     }
   31333   else if (AUTO_IS_DECLTYPE (auto_node))
   31334     {
   31335       const bool id = unparenthesized_id_or_class_member_access_p (init);
   31336       tree deduced = finish_decltype_type (init, id, complain);
   31337       deduced = canonicalize_type_argument (deduced, complain);
   31338       if (deduced == error_mark_node)
   31339 	return error_mark_node;
   31340       targs = make_tree_vec (1);
   31341       TREE_VEC_ELT (targs, 0) = deduced;
   31342     }
   31343   else
   31344     {
   31345       if (error_operand_p (init))
   31346 	return error_mark_node;
   31347 
   31348       tree parms = build_tree_list (NULL_TREE, type);
   31349       tree tparms;
   31350 
   31351       if (flag_concepts_ts)
   31352 	tparms = extract_autos (type);
   31353       else
   31354 	{
   31355 	  tparms = make_tree_vec (1);
   31356 	  TREE_VEC_ELT (tparms, 0)
   31357 	    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
   31358 	}
   31359 
   31360       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
   31361       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
   31362 				       DEDUCE_CALL,
   31363 				       NULL, /*explain_p=*/false);
   31364       if (val > 0)
   31365 	{
   31366 	  if (processing_template_decl)
   31367 	    /* Try again at instantiation time.  */
   31368 	    return type;
   31369 	  if (type && type != error_mark_node
   31370 	      && (complain & tf_error))
   31371 	    /* If type is error_mark_node a diagnostic must have been
   31372 	       emitted by now.  Also, having a mention to '<type error>'
   31373 	       in the diagnostic is not really useful to the user.  */
   31374 	    {
   31375 	      if (cfun
   31376 		  && FNDECL_USED_AUTO (current_function_decl)
   31377 		  && (auto_node
   31378 		      == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
   31379 		  && LAMBDA_FUNCTION_P (current_function_decl))
   31380 		error_at (loc, "unable to deduce lambda return type from %qE",
   31381 			  init);
   31382 	      else
   31383 		error_at (loc, "unable to deduce %qT from %qE", type, init);
   31384 	      type_unification_real (tparms, targs, parms, &init, 1, 0,
   31385 				     DEDUCE_CALL,
   31386 				     NULL, /*explain_p=*/true);
   31387 	    }
   31388 	  return error_mark_node;
   31389 	}
   31390     }
   31391 
   31392   /* Check any placeholder constraints against the deduced type. */
   31393   if (processing_template_decl && context == adc_unify)
   31394     /* Constraints will be checked after deduction.  */;
   31395   else if (tree constr = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
   31396     {
   31397       if (processing_template_decl)
   31398 	{
   31399 	  gcc_checking_assert (context == adc_variable_type
   31400 			       || context == adc_return_type
   31401 			       || context == adc_decomp_type);
   31402 	  gcc_checking_assert (!type_dependent_expression_p (init));
   31403 	  /* If the constraint is dependent, we need to wait until
   31404 	     instantiation time to resolve the placeholder.  */
   31405 	  if (placeholder_type_constraint_dependent_p (constr))
   31406 	    return type;
   31407 	}
   31408 
   31409       if (context == adc_return_type
   31410 	  || context == adc_variable_type
   31411 	  || context == adc_decomp_type)
   31412 	if (tree fn = current_function_decl)
   31413 	  if (DECL_TEMPLATE_INFO (fn) || LAMBDA_FUNCTION_P (fn))
   31414 	    {
   31415 	      outer_targs = DECL_TEMPLATE_INFO (fn)
   31416 		? DECL_TI_ARGS (fn) : NULL_TREE;
   31417 	      if (LAMBDA_FUNCTION_P (fn))
   31418 		{
   31419 		  /* As in satisfy_declaration_constraints.  */
   31420 		  tree regen_args = lambda_regenerating_args (fn);
   31421 		  if (outer_targs)
   31422 		    outer_targs = add_to_template_args (regen_args, outer_targs);
   31423 		  else
   31424 		    outer_targs = regen_args;
   31425 		}
   31426 	    }
   31427 
   31428       tree full_targs = outer_targs;
   31429       if (context == adc_unify && tmpl)
   31430 	full_targs = add_outermost_template_args (tmpl, full_targs);
   31431       full_targs = add_to_template_args (full_targs, targs);
   31432 
   31433       /* HACK: Compensate for callers not always communicating all levels of
   31434 	 outer template arguments by filling in the outermost missing levels
   31435 	 with dummy levels before checking satisfaction.  We'll still crash
   31436 	 if the constraint depends on a template argument belonging to one of
   31437 	 these missing levels, but this hack otherwise allows us to handle a
   31438 	 large subset of possible constraints (including all non-dependent
   31439 	 constraints).  */
   31440       if (int missing_levels = (TEMPLATE_TYPE_ORIG_LEVEL (auto_node)
   31441 				- TMPL_ARGS_DEPTH (full_targs)))
   31442 	{
   31443 	  tree dummy_levels = make_tree_vec (missing_levels);
   31444 	  for (int i = 0; i < missing_levels; ++i)
   31445 	    TREE_VEC_ELT (dummy_levels, i) = make_tree_vec (0);
   31446 	  full_targs = add_to_template_args (dummy_levels, full_targs);
   31447 	}
   31448 
   31449       if (!constraints_satisfied_p (auto_node, full_targs))
   31450 	{
   31451 	  if (complain & tf_warning_or_error)
   31452 	    {
   31453 	      auto_diagnostic_group d;
   31454 	      switch (context)
   31455 		{
   31456 		case adc_unspecified:
   31457 		case adc_unify:
   31458 		  error_at (loc, "placeholder constraints not satisfied");
   31459 		  break;
   31460 		case adc_variable_type:
   31461 		case adc_decomp_type:
   31462 		  error_at (loc, "deduced initializer does not satisfy "
   31463 			    "placeholder constraints");
   31464 		  break;
   31465 		case adc_return_type:
   31466 		  error_at (loc, "deduced return type does not satisfy "
   31467 			    "placeholder constraints");
   31468 		  break;
   31469 		case adc_requirement:
   31470 		  error_at (loc, "deduced expression type does not satisfy "
   31471 			    "placeholder constraints");
   31472 		  break;
   31473 		}
   31474 	      diagnose_constraints (loc, auto_node, full_targs);
   31475 	    }
   31476 	  return error_mark_node;
   31477 	}
   31478     }
   31479 
   31480   if (TEMPLATE_TYPE_LEVEL (auto_node) == 0)
   31481     {
   31482       /* Substitute this level-less auto via tsubst by temporarily
   31483 	 overriding its level to 1.  */
   31484       TEMPLATE_TYPE_LEVEL (auto_node) = 1;
   31485       type = tsubst (type, targs, complain, NULL_TREE);
   31486       TEMPLATE_TYPE_LEVEL (auto_node) = 0;
   31487       return type;
   31488     }
   31489 
   31490   if (TEMPLATE_TYPE_LEVEL (auto_node) == 1)
   31491     /* The outer template arguments are already substituted into type
   31492        (but we still may have used them for constraint checking above).  */;
   31493   else if (context == adc_unify)
   31494     targs = add_to_template_args (outer_targs, targs);
   31495   else if (processing_template_decl)
   31496     targs = add_to_template_args (current_template_args (), targs);
   31497   return tsubst (type, targs, complain, NULL_TREE);
   31498 }
   31499 
   31500 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
   31501    result.  */
   31502 
   31503 tree
   31504 splice_late_return_type (tree type, tree late_return_type)
   31505 {
   31506   if (late_return_type)
   31507     {
   31508       gcc_assert (is_auto (type) || seen_error ());
   31509       return late_return_type;
   31510     }
   31511 
   31512   if (tree auto_node = find_type_usage (type, is_auto))
   31513     if (TEMPLATE_TYPE_LEVEL (auto_node) <= current_template_depth)
   31514       {
   31515 	/* In an abbreviated function template we didn't know we were dealing
   31516 	   with a function template when we saw the auto return type, so rebuild
   31517 	   the return type using an auto with the correct level.  */
   31518 	tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
   31519 	tree auto_vec = make_tree_vec (1);
   31520 	TREE_VEC_ELT (auto_vec, 0) = new_auto;
   31521 	tree targs = add_outermost_template_args (current_template_args (),
   31522 						  auto_vec);
   31523 	/* Also rebuild the constraint info in terms of the new auto.  */
   31524 	if (tree ci = PLACEHOLDER_TYPE_CONSTRAINTS_INFO (auto_node))
   31525 	  PLACEHOLDER_TYPE_CONSTRAINTS_INFO (new_auto)
   31526 	    = build_tree_list (current_template_parms,
   31527 			       tsubst_constraint (TREE_VALUE (ci), targs,
   31528 						  tf_none, NULL_TREE));
   31529 	TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
   31530 	return tsubst (type, targs, tf_none, NULL_TREE);
   31531       }
   31532   return type;
   31533 }
   31534 
   31535 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
   31536    'decltype(auto)' or a deduced class template.  */
   31537 
   31538 bool
   31539 is_auto (const_tree type)
   31540 {
   31541   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
   31542       && (TYPE_IDENTIFIER (type) == auto_identifier
   31543 	  || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
   31544     return true;
   31545   else
   31546     return false;
   31547 }
   31548 
   31549 /* for_each_template_parm callback for type_uses_auto.  */
   31550 
   31551 int
   31552 is_auto_r (tree tp, void */*data*/)
   31553 {
   31554   return is_auto (tp);
   31555 }
   31556 
   31557 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
   31558    a use of `auto'.  Returns NULL_TREE otherwise.  */
   31559 
   31560 tree
   31561 type_uses_auto (tree type)
   31562 {
   31563   if (type == NULL_TREE)
   31564     return NULL_TREE;
   31565 
   31566   /* For parameter packs, check the contents of the pack.  */
   31567   if (PACK_EXPANSION_P (type))
   31568     type = PACK_EXPANSION_PATTERN (type);
   31569 
   31570   if (flag_concepts_ts)
   31571     {
   31572       /* The Concepts TS allows multiple autos in one type-specifier; just
   31573 	 return the first one we find, do_auto_deduction will collect all of
   31574 	 them.  */
   31575       if (uses_template_parms (type))
   31576 	return for_each_template_parm (type, is_auto_r, /*data*/NULL,
   31577 				       /*visited*/NULL, /*nondeduced*/false);
   31578       else
   31579 	return NULL_TREE;
   31580     }
   31581   else
   31582     return find_type_usage (type, is_auto);
   31583 }
   31584 
   31585 /* Report ill-formed occurrences of auto types in ARGUMENTS.  If
   31586    concepts are enabled, auto is acceptable in template arguments, but
   31587    only when TEMPL identifies a template class.  Return TRUE if any
   31588    such errors were reported.  */
   31589 
   31590 bool
   31591 check_auto_in_tmpl_args (tree tmpl, tree args)
   31592 {
   31593   if (!flag_concepts_ts)
   31594     /* Only the concepts TS allows 'auto' as a type-id; it'd otherwise
   31595        have already been rejected by the parser more generally.  */
   31596     return false;
   31597 
   31598   /* If there were previous errors, nevermind.  */
   31599   if (!args || TREE_CODE (args) != TREE_VEC)
   31600     return false;
   31601 
   31602   /* If TMPL is an identifier, we're parsing and we can't tell yet
   31603      whether TMPL is supposed to be a type, a function or a variable.
   31604      We'll only be able to tell during template substitution, so we
   31605      expect to be called again then.  If concepts are enabled and we
   31606      know we have a type, we're ok.  */
   31607   if (identifier_p (tmpl)
   31608       || (DECL_P (tmpl)
   31609 	  &&  (DECL_TYPE_TEMPLATE_P (tmpl)
   31610 	       || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))))
   31611     return false;
   31612 
   31613   /* Quickly search for any occurrences of auto; usually there won't
   31614      be any, and then we'll avoid allocating the vector.  */
   31615   if (!type_uses_auto (args))
   31616     return false;
   31617 
   31618   bool errors = false;
   31619 
   31620   tree vec = extract_autos (args);
   31621   for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
   31622     {
   31623       tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
   31624       error_at (DECL_SOURCE_LOCATION (xauto),
   31625 		"invalid use of %qT in template argument", xauto);
   31626       errors = true;
   31627     }
   31628 
   31629   return errors;
   31630 }
   31631 
   31632 /* Recursively walk over && expressions searching for EXPR. Return a reference
   31633    to that expression.  */
   31634 
   31635 static tree *find_template_requirement (tree *t, tree key)
   31636 {
   31637   if (*t == key)
   31638     return t;
   31639   if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
   31640     {
   31641       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
   31642 	return p;
   31643       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
   31644 	return p;
   31645     }
   31646   return 0;
   31647 }
   31648 
   31649 /* Convert the generic type parameters in PARM that match the types given in the
   31650    range [START_IDX, END_IDX) from the current_template_parms into generic type
   31651    packs.  */
   31652 
   31653 tree
   31654 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
   31655 {
   31656   tree current = current_template_parms;
   31657   int depth = TMPL_PARMS_DEPTH (current);
   31658   current = INNERMOST_TEMPLATE_PARMS (current);
   31659   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
   31660 
   31661   for (int i = 0; i < start_idx; ++i)
   31662     TREE_VEC_ELT (replacement, i)
   31663       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
   31664 
   31665   for (int i = start_idx; i < end_idx; ++i)
   31666     {
   31667       /* Create a distinct parameter pack type from the current parm and add it
   31668 	 to the replacement args to tsubst below into the generic function
   31669 	 parameter.  */
   31670       tree node = TREE_VEC_ELT (current, i);
   31671       tree o = TREE_TYPE (TREE_VALUE (node));
   31672       tree t = copy_type (o);
   31673       TEMPLATE_TYPE_PARM_INDEX (t)
   31674 	= reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
   31675 				      t, 0, 0, tf_none);
   31676       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
   31677       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
   31678       TYPE_MAIN_VARIANT (t) = t;
   31679       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
   31680       TYPE_CANONICAL (t) = canonical_type_parameter (t);
   31681       TREE_VEC_ELT (replacement, i) = t;
   31682 
   31683       /* Replace the current template parameter with new pack.  */
   31684       TREE_VALUE (node) = TREE_CHAIN (t);
   31685 
   31686       /* Surgically adjust the associated constraint of adjusted parameter
   31687          and it's corresponding contribution to the current template
   31688          requirements.  */
   31689       if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
   31690 	{
   31691 	  tree id = unpack_concept_check (constr);
   31692 	  TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
   31693 	  /* Use UNKNOWN_LOCATION so write_template_args can tell the
   31694 	     difference between this and a fold the user wrote.  */
   31695 	  location_t loc = UNKNOWN_LOCATION;
   31696 	  tree fold = finish_left_unary_fold_expr (loc, constr,
   31697 						   TRUTH_ANDIF_EXPR);
   31698 	  TEMPLATE_PARM_CONSTRAINTS (node) = fold;
   31699 
   31700 	  /* If there was a constraint, we also need to replace that in
   31701 	     the template requirements, which we've already built.  */
   31702 	  tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
   31703 	  reqs = find_template_requirement (reqs, constr);
   31704 	  *reqs = fold;
   31705 	}
   31706     }
   31707 
   31708   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
   31709     TREE_VEC_ELT (replacement, i)
   31710       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
   31711 
   31712   /* If there are more levels then build up the replacement with the outer
   31713      template parms.  */
   31714   if (depth > 1)
   31715     replacement = add_to_template_args (template_parms_to_args
   31716 					(TREE_CHAIN (current_template_parms)),
   31717 					replacement);
   31718 
   31719   return tsubst (parm, replacement, tf_none, NULL_TREE);
   31720 }
   31721 
   31722 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
   31723    0..N-1.  */
   31724 
   31725 void
   31726 declare_integer_pack (void)
   31727 {
   31728   tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
   31729 			       build_function_type_list (integer_type_node,
   31730 							 integer_type_node,
   31731 							 NULL_TREE),
   31732 			       NULL_TREE, ECF_CONST);
   31733   DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
   31734   set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
   31735 			      CP_BUILT_IN_INTEGER_PACK);
   31736 }
   31737 
   31738 /* Walk the decl or type specialization table calling FN on each
   31739    entry.  */
   31740 
   31741 void
   31742 walk_specializations (bool decls_p,
   31743 		      void (*fn) (bool decls_p, spec_entry *entry, void *data),
   31744 		      void *data)
   31745 {
   31746   spec_hash_table *table = decls_p ? decl_specializations
   31747     : type_specializations;
   31748   spec_hash_table::iterator end (table->end ());
   31749   for (spec_hash_table::iterator iter (table->begin ()); iter != end; ++iter)
   31750     fn (decls_p, *iter, data);
   31751 }
   31752 
   31753 /* Lookup the specialization of *ELT, in the decl or type
   31754    specialization table.  Return the SPEC that's already there, or
   31755    NULL if nothing.  */
   31756 
   31757 tree
   31758 match_mergeable_specialization (bool decl_p, spec_entry *elt)
   31759 {
   31760   hash_table<spec_hasher> *specializations
   31761     = decl_p ? decl_specializations : type_specializations;
   31762   hashval_t hash = spec_hasher::hash (elt);
   31763   auto *slot = specializations->find_slot_with_hash (elt, hash, NO_INSERT);
   31764 
   31765   if (slot)
   31766     return (*slot)->spec;
   31767 
   31768   return NULL_TREE;
   31769 }
   31770 
   31771 /* Return flags encoding whether SPEC is on the instantiation and/or
   31772    specialization lists of TMPL.  */
   31773 
   31774 unsigned
   31775 get_mergeable_specialization_flags (tree tmpl, tree decl)
   31776 {
   31777   unsigned flags = 0;
   31778 
   31779   for (tree inst = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
   31780        inst; inst = TREE_CHAIN (inst))
   31781     if (TREE_VALUE (inst) == decl)
   31782       {
   31783 	flags |= 1;
   31784 	break;
   31785       }
   31786 
   31787   if (CLASS_TYPE_P (TREE_TYPE (decl))
   31788       && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))
   31789       && CLASSTYPE_USE_TEMPLATE (TREE_TYPE (decl)) == 2)
   31790     /* Only need to search if DECL is a partial specialization.  */
   31791     for (tree part = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
   31792 	 part; part = TREE_CHAIN (part))
   31793       if (TREE_VALUE (part) == decl)
   31794 	{
   31795 	  flags |= 2;
   31796 	  break;
   31797 	}
   31798 
   31799   return flags;
   31800 }
   31801 
   31802 /* Add a new specialization described by SPEC.  DECL is the
   31803    maybe-template decl and FLAGS is as returned from
   31804    get_mergeable_specialization_flags.  */
   31805 
   31806 void
   31807 add_mergeable_specialization (bool decl_p, spec_entry *elt, tree decl,
   31808 			      unsigned flags)
   31809 {
   31810   hashval_t hash = spec_hasher::hash (elt);
   31811   if (decl_p)
   31812     {
   31813       auto *slot = decl_specializations->find_slot_with_hash (elt, hash, INSERT);
   31814 
   31815       gcc_checking_assert (!*slot);
   31816       auto entry = ggc_alloc<spec_entry> ();
   31817       *entry = *elt;
   31818       *slot = entry;
   31819     }
   31820   else
   31821     {
   31822       auto *slot = type_specializations->find_slot_with_hash (elt, hash, INSERT);
   31823 
   31824       /* We don't distinguish different constrained partial type
   31825 	 specializations, so there could be duplicates.  Everything else
   31826 	 must be new.   */
   31827       if (!(flags & 2 && *slot))
   31828 	{
   31829 	  gcc_checking_assert (!*slot);
   31830 
   31831 	  auto entry = ggc_alloc<spec_entry> ();
   31832 	  *entry = *elt;
   31833 	  *slot = entry;
   31834 	}
   31835     }
   31836 
   31837   if (flags & 1)
   31838     DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl)
   31839       = tree_cons (elt->args, decl, DECL_TEMPLATE_INSTANTIATIONS (elt->tmpl));
   31840 
   31841   if (flags & 2)
   31842     {
   31843       /* A partial specialization.  */
   31844       tree cons = tree_cons (elt->args, decl,
   31845 			     DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl));
   31846       TREE_TYPE (cons) = decl_p ? TREE_TYPE (elt->spec) : elt->spec;
   31847       DECL_TEMPLATE_SPECIALIZATIONS (elt->tmpl) = cons;
   31848     }
   31849 }
   31850 
   31851 /* Set up the hash tables for template instantiations.  */
   31852 
   31853 void
   31854 init_template_processing (void)
   31855 {
   31856   decl_specializations = hash_table<spec_hasher>::create_ggc (37);
   31857   type_specializations = hash_table<spec_hasher>::create_ggc (37);
   31858 
   31859   if (cxx_dialect >= cxx11)
   31860     declare_integer_pack ();
   31861 }
   31862 
   31863 /* Print stats about the template hash tables for -fstats.  */
   31864 
   31865 void
   31866 print_template_statistics (void)
   31867 {
   31868   fprintf (stderr, "decl_specializations: size " HOST_SIZE_T_PRINT_DEC ", "
   31869 	   HOST_SIZE_T_PRINT_DEC " elements, %f collisions\n",
   31870 	   (fmt_size_t) decl_specializations->size (),
   31871 	   (fmt_size_t) decl_specializations->elements (),
   31872 	   decl_specializations->collisions ());
   31873   fprintf (stderr, "type_specializations: size " HOST_SIZE_T_PRINT_DEC ", "
   31874 	   HOST_SIZE_T_PRINT_DEC " elements, %f collisions\n",
   31875 	   (fmt_size_t) type_specializations->size (),
   31876 	   (fmt_size_t) type_specializations->elements (),
   31877 	   type_specializations->collisions ());
   31878 }
   31879 
   31880 #if CHECKING_P
   31881 
   31882 namespace selftest {
   31883 
   31884 /* Verify that type_dependent_expression_p () works correctly, even
   31885    in the presence of location wrapper nodes.  */
   31886 
   31887 static void
   31888 test_type_dependent_expression_p ()
   31889 {
   31890   location_t loc = BUILTINS_LOCATION;
   31891 
   31892   tree name = get_identifier ("foo");
   31893 
   31894   /* If no templates are involved, nothing is type-dependent.  */
   31895   gcc_assert (!processing_template_decl);
   31896   ASSERT_FALSE (type_dependent_expression_p (name));
   31897 
   31898   ++processing_template_decl;
   31899 
   31900   /* Within a template, an unresolved name is always type-dependent.  */
   31901   ASSERT_TRUE (type_dependent_expression_p (name));
   31902 
   31903   /* Ensure it copes with NULL_TREE and errors.  */
   31904   ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
   31905   ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
   31906 
   31907   /* A USING_DECL in a template should be type-dependent, even if wrapped
   31908      with a location wrapper (PR c++/83799).  */
   31909   tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
   31910   TREE_TYPE (using_decl) = integer_type_node;
   31911   ASSERT_TRUE (type_dependent_expression_p (using_decl));
   31912   tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
   31913   ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
   31914   ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
   31915 
   31916   --processing_template_decl;
   31917 }
   31918 
   31919 /* Run all of the selftests within this file.  */
   31920 
   31921 void
   31922 cp_pt_cc_tests ()
   31923 {
   31924   test_type_dependent_expression_p ();
   31925 }
   31926 
   31927 } // namespace selftest
   31928 
   31929 #endif /* #if CHECKING_P */
   31930 
   31931 #include "gt-cp-pt.h"
   31932