xref: /dragonfly/contrib/gcc-8.0/gcc/cp/pt.c (revision 7bcb6caf)
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2    Copyright (C) 1992-2018 Free Software Foundation, Inc.
3    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4    Rewritten by Jason Merrill (jason@cygnus.com).
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 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "cp-tree.h"
31 #include "timevar.h"
32 #include "stringpool.h"
33 #include "varasm.h"
34 #include "attribs.h"
35 #include "stor-layout.h"
36 #include "intl.h"
37 #include "c-family/c-objc.h"
38 #include "cp-objcp-common.h"
39 #include "toplev.h"
40 #include "tree-iterator.h"
41 #include "type-utils.h"
42 #include "gimplify.h"
43 #include "gcc-rich-location.h"
44 #include "selftest.h"
45 
46 /* The type of functions taking a tree, and some additional data, and
47    returning an int.  */
48 typedef int (*tree_fn_t) (tree, void*);
49 
50 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
51    instantiations have been deferred, either because their definitions
52    were not yet available, or because we were putting off doing the work.  */
53 struct GTY ((chain_next ("%h.next"))) pending_template
54 {
55   struct pending_template *next;
56   struct tinst_level *tinst;
57 };
58 
59 static GTY(()) struct pending_template *pending_templates;
60 static GTY(()) struct pending_template *last_pending_template;
61 
62 int processing_template_parmlist;
63 static int template_header_count;
64 
65 static GTY(()) tree saved_trees;
66 static vec<int> inline_parm_levels;
67 
68 static GTY(()) struct tinst_level *current_tinst_level;
69 
70 static GTY(()) tree saved_access_scope;
71 
72 /* Live only within one (recursive) call to tsubst_expr.  We use
73    this to pass the statement expression node from the STMT_EXPR
74    to the EXPR_STMT that is its result.  */
75 static tree cur_stmt_expr;
76 
77 // -------------------------------------------------------------------------- //
78 // Local Specialization Stack
79 //
80 // Implementation of the RAII helper for creating new local
81 // specializations.
82 local_specialization_stack::local_specialization_stack (lss_policy policy)
83   : saved (local_specializations)
84 {
85   if (policy == lss_blank || !saved)
86     local_specializations = new hash_map<tree, tree>;
87   else
88     local_specializations = new hash_map<tree, tree>(*saved);
89 }
90 
91 local_specialization_stack::~local_specialization_stack ()
92 {
93   delete local_specializations;
94   local_specializations = saved;
95 }
96 
97 /* True if we've recursed into fn_type_unification too many times.  */
98 static bool excessive_deduction_depth;
99 
100 struct GTY((for_user)) spec_entry
101 {
102   tree tmpl;
103   tree args;
104   tree spec;
105 };
106 
107 struct spec_hasher : ggc_ptr_hash<spec_entry>
108 {
109   static hashval_t hash (spec_entry *);
110   static bool equal (spec_entry *, spec_entry *);
111 };
112 
113 static GTY (()) hash_table<spec_hasher> *decl_specializations;
114 
115 static GTY (()) hash_table<spec_hasher> *type_specializations;
116 
117 /* Contains canonical template parameter types. The vector is indexed by
118    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
119    TREE_LIST, whose TREE_VALUEs contain the canonical template
120    parameters of various types and levels.  */
121 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
122 
123 #define UNIFY_ALLOW_NONE 0
124 #define UNIFY_ALLOW_MORE_CV_QUAL 1
125 #define UNIFY_ALLOW_LESS_CV_QUAL 2
126 #define UNIFY_ALLOW_DERIVED 4
127 #define UNIFY_ALLOW_INTEGER 8
128 #define UNIFY_ALLOW_OUTER_LEVEL 16
129 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
130 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
131 
132 enum template_base_result {
133   tbr_incomplete_type,
134   tbr_ambiguous_baseclass,
135   tbr_success
136 };
137 
138 static void push_access_scope (tree);
139 static void pop_access_scope (tree);
140 static bool resolve_overloaded_unification (tree, tree, tree, tree,
141 					    unification_kind_t, int,
142 					    bool);
143 static int try_one_overload (tree, tree, tree, tree, tree,
144 			     unification_kind_t, int, bool, bool);
145 static int unify (tree, tree, tree, tree, int, bool);
146 static void add_pending_template (tree);
147 static tree reopen_tinst_level (struct tinst_level *);
148 static tree tsubst_initializer_list (tree, tree);
149 static tree get_partial_spec_bindings (tree, tree, tree);
150 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
151 				   bool, bool);
152 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
153 					      bool, bool);
154 static void tsubst_enum	(tree, tree, tree);
155 static tree add_to_template_args (tree, tree);
156 static tree add_outermost_template_args (tree, tree);
157 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
158 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
159 					     tree);
160 static int type_unification_real (tree, tree, tree, const tree *,
161 				  unsigned int, int, unification_kind_t, int,
162 				  vec<deferred_access_check, va_gc> **,
163 				  bool);
164 static void note_template_header (int);
165 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
166 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
167 static tree convert_template_argument (tree, tree, tree,
168 				       tsubst_flags_t, int, tree);
169 static tree for_each_template_parm (tree, tree_fn_t, void*,
170 				    hash_set<tree> *, bool, tree_fn_t = NULL);
171 static tree expand_template_argument_pack (tree);
172 static tree build_template_parm_index (int, int, int, tree, tree);
173 static bool inline_needs_template_parms (tree, bool);
174 static void push_inline_template_parms_recursive (tree, int);
175 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
176 static int mark_template_parm (tree, void *);
177 static int template_parm_this_level_p (tree, void *);
178 static tree tsubst_friend_function (tree, tree);
179 static tree tsubst_friend_class (tree, tree);
180 static int can_complete_type_without_circularity (tree);
181 static tree get_bindings (tree, tree, tree, bool);
182 static int template_decl_level (tree);
183 static int check_cv_quals_for_unify (int, tree, tree);
184 static void template_parm_level_and_index (tree, int*, int*);
185 static int unify_pack_expansion (tree, tree, tree,
186 				 tree, unification_kind_t, bool, bool);
187 static tree copy_template_args (tree);
188 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
191 static tree most_specialized_partial_spec (tree, tsubst_flags_t);
192 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
193 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
194 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
195 static bool check_specialization_scope (void);
196 static tree process_partial_specialization (tree);
197 static void set_current_access_from_decl (tree);
198 static enum template_base_result get_template_base (tree, tree, tree, tree,
199 						    bool , tree *);
200 static tree try_class_unification (tree, tree, tree, tree, bool);
201 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
202 					   tree, tree);
203 static bool template_template_parm_bindings_ok_p (tree, tree);
204 static void tsubst_default_arguments (tree, tsubst_flags_t);
205 static tree for_each_template_parm_r (tree *, int *, void *);
206 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
207 static void copy_default_args_to_explicit_spec (tree);
208 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
209 static bool dependent_template_arg_p (tree);
210 static bool any_template_arguments_need_structural_equality_p (tree);
211 static bool dependent_type_p_r (tree);
212 static tree tsubst_copy	(tree, tree, tsubst_flags_t, tree);
213 static tree tsubst_decl (tree, tree, tsubst_flags_t);
214 static void perform_typedefs_access_check (tree tmpl, tree targs);
215 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
216 							location_t);
217 static tree listify (tree);
218 static tree listify_autos (tree, tree);
219 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
220 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
221 static bool complex_alias_template_p (const_tree tmpl);
222 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
223 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
224 static tree make_argument_pack (tree);
225 static void register_parameter_specializations (tree, tree);
226 static tree enclosing_instantiation_of (tree tctx);
227 
228 /* Make the current scope suitable for access checking when we are
229    processing T.  T can be FUNCTION_DECL for instantiated function
230    template, VAR_DECL for static member variable, or TYPE_DECL for
231    alias template (needed by instantiate_decl).  */
232 
233 static void
234 push_access_scope (tree t)
235 {
236   gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
237 	      || TREE_CODE (t) == TYPE_DECL);
238 
239   if (DECL_FRIEND_CONTEXT (t))
240     push_nested_class (DECL_FRIEND_CONTEXT (t));
241   else if (DECL_CLASS_SCOPE_P (t))
242     push_nested_class (DECL_CONTEXT (t));
243   else
244     push_to_top_level ();
245 
246   if (TREE_CODE (t) == FUNCTION_DECL)
247     {
248       saved_access_scope = tree_cons
249 	(NULL_TREE, current_function_decl, saved_access_scope);
250       current_function_decl = t;
251     }
252 }
253 
254 /* Restore the scope set up by push_access_scope.  T is the node we
255    are processing.  */
256 
257 static void
258 pop_access_scope (tree t)
259 {
260   if (TREE_CODE (t) == FUNCTION_DECL)
261     {
262       current_function_decl = TREE_VALUE (saved_access_scope);
263       saved_access_scope = TREE_CHAIN (saved_access_scope);
264     }
265 
266   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
267     pop_nested_class ();
268   else
269     pop_from_top_level ();
270 }
271 
272 /* Do any processing required when DECL (a member template
273    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
274    to DECL, unless it is a specialization, in which case the DECL
275    itself is returned.  */
276 
277 tree
278 finish_member_template_decl (tree decl)
279 {
280   if (decl == error_mark_node)
281     return error_mark_node;
282 
283   gcc_assert (DECL_P (decl));
284 
285   if (TREE_CODE (decl) == TYPE_DECL)
286     {
287       tree type;
288 
289       type = TREE_TYPE (decl);
290       if (type == error_mark_node)
291 	return error_mark_node;
292       if (MAYBE_CLASS_TYPE_P (type)
293 	  && CLASSTYPE_TEMPLATE_INFO (type)
294 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
295 	{
296 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
297 	  check_member_template (tmpl);
298 	  return tmpl;
299 	}
300       return NULL_TREE;
301     }
302   else if (TREE_CODE (decl) == FIELD_DECL)
303     error ("data member %qD cannot be a member template", decl);
304   else if (DECL_TEMPLATE_INFO (decl))
305     {
306       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
307 	{
308 	  check_member_template (DECL_TI_TEMPLATE (decl));
309 	  return DECL_TI_TEMPLATE (decl);
310 	}
311       else
312 	return decl;
313     }
314   else
315     error ("invalid member template declaration %qD", decl);
316 
317   return error_mark_node;
318 }
319 
320 /* Create a template info node.  */
321 
322 tree
323 build_template_info (tree template_decl, tree template_args)
324 {
325   tree result = make_node (TEMPLATE_INFO);
326   TI_TEMPLATE (result) = template_decl;
327   TI_ARGS (result) = template_args;
328   return result;
329 }
330 
331 /* Return the template info node corresponding to T, whatever T is.  */
332 
333 tree
334 get_template_info (const_tree t)
335 {
336   tree tinfo = NULL_TREE;
337 
338   if (!t || t == error_mark_node)
339     return NULL;
340 
341   if (TREE_CODE (t) == NAMESPACE_DECL
342       || TREE_CODE (t) == PARM_DECL)
343     return NULL;
344 
345   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
346     tinfo = DECL_TEMPLATE_INFO (t);
347 
348   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
349     t = TREE_TYPE (t);
350 
351   if (OVERLOAD_TYPE_P (t))
352     tinfo = TYPE_TEMPLATE_INFO (t);
353   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
354     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
355 
356   return tinfo;
357 }
358 
359 /* Returns the template nesting level of the indicated class TYPE.
360 
361    For example, in:
362      template <class T>
363      struct A
364      {
365        template <class U>
366        struct B {};
367      };
368 
369    A<T>::B<U> has depth two, while A<T> has depth one.
370    Both A<T>::B<int> and A<int>::B<U> have depth one, if
371    they are instantiations, not specializations.
372 
373    This function is guaranteed to return 0 if passed NULL_TREE so
374    that, for example, `template_class_depth (current_class_type)' is
375    always safe.  */
376 
377 int
378 template_class_depth (tree type)
379 {
380   int depth;
381 
382   for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
383     {
384       tree tinfo = get_template_info (type);
385 
386       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
387 	  && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
388 	++depth;
389 
390       if (DECL_P (type))
391 	type = CP_DECL_CONTEXT (type);
392       else if (LAMBDA_TYPE_P (type))
393 	type = LAMBDA_TYPE_EXTRA_SCOPE (type);
394       else
395 	type = CP_TYPE_CONTEXT (type);
396     }
397 
398   return depth;
399 }
400 
401 /* Subroutine of maybe_begin_member_template_processing.
402    Returns true if processing DECL needs us to push template parms.  */
403 
404 static bool
405 inline_needs_template_parms (tree decl, bool nsdmi)
406 {
407   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
408     return false;
409 
410   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
411 	  > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
412 }
413 
414 /* Subroutine of maybe_begin_member_template_processing.
415    Push the template parms in PARMS, starting from LEVELS steps into the
416    chain, and ending at the beginning, since template parms are listed
417    innermost first.  */
418 
419 static void
420 push_inline_template_parms_recursive (tree parmlist, int levels)
421 {
422   tree parms = TREE_VALUE (parmlist);
423   int i;
424 
425   if (levels > 1)
426     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
427 
428   ++processing_template_decl;
429   current_template_parms
430     = tree_cons (size_int (processing_template_decl),
431 		 parms, current_template_parms);
432   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
433 
434   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
435 	       NULL);
436   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
437     {
438       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
439 
440       if (error_operand_p (parm))
441 	continue;
442 
443       gcc_assert (DECL_P (parm));
444 
445       switch (TREE_CODE (parm))
446 	{
447 	case TYPE_DECL:
448 	case TEMPLATE_DECL:
449 	  pushdecl (parm);
450 	  break;
451 
452 	case PARM_DECL:
453 	  /* Push the CONST_DECL.  */
454 	  pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
455 	  break;
456 
457 	default:
458 	  gcc_unreachable ();
459 	}
460     }
461 }
462 
463 /* Restore the template parameter context for a member template, a
464    friend template defined in a class definition, or a non-template
465    member of template class.  */
466 
467 void
468 maybe_begin_member_template_processing (tree decl)
469 {
470   tree parms;
471   int levels = 0;
472   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
473 
474   if (nsdmi)
475     {
476       tree ctx = DECL_CONTEXT (decl);
477       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
478 	      /* Disregard full specializations (c++/60999).  */
479 	      && uses_template_parms (ctx)
480 	      ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
481     }
482 
483   if (inline_needs_template_parms (decl, nsdmi))
484     {
485       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
486       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
487 
488       if (DECL_TEMPLATE_SPECIALIZATION (decl))
489 	{
490 	  --levels;
491 	  parms = TREE_CHAIN (parms);
492 	}
493 
494       push_inline_template_parms_recursive (parms, levels);
495     }
496 
497   /* Remember how many levels of template parameters we pushed so that
498      we can pop them later.  */
499   inline_parm_levels.safe_push (levels);
500 }
501 
502 /* Undo the effects of maybe_begin_member_template_processing.  */
503 
504 void
505 maybe_end_member_template_processing (void)
506 {
507   int i;
508   int last;
509 
510   if (inline_parm_levels.length () == 0)
511     return;
512 
513   last = inline_parm_levels.pop ();
514   for (i = 0; i < last; ++i)
515     {
516       --processing_template_decl;
517       current_template_parms = TREE_CHAIN (current_template_parms);
518       poplevel (0, 0, 0);
519     }
520 }
521 
522 /* Return a new template argument vector which contains all of ARGS,
523    but has as its innermost set of arguments the EXTRA_ARGS.  */
524 
525 static tree
526 add_to_template_args (tree args, tree extra_args)
527 {
528   tree new_args;
529   int extra_depth;
530   int i;
531   int j;
532 
533   if (args == NULL_TREE || extra_args == error_mark_node)
534     return extra_args;
535 
536   extra_depth = TMPL_ARGS_DEPTH (extra_args);
537   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
538 
539   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
540     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
541 
542   for (j = 1; j <= extra_depth; ++j, ++i)
543     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
544 
545   return new_args;
546 }
547 
548 /* Like add_to_template_args, but only the outermost ARGS are added to
549    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
550    (EXTRA_ARGS) levels are added.  This function is used to combine
551    the template arguments from a partial instantiation with the
552    template arguments used to attain the full instantiation from the
553    partial instantiation.  */
554 
555 static tree
556 add_outermost_template_args (tree args, tree extra_args)
557 {
558   tree new_args;
559 
560   /* If there are more levels of EXTRA_ARGS than there are ARGS,
561      something very fishy is going on.  */
562   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
563 
564   /* If *all* the new arguments will be the EXTRA_ARGS, just return
565      them.  */
566   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
567     return extra_args;
568 
569   /* For the moment, we make ARGS look like it contains fewer levels.  */
570   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
571 
572   new_args = add_to_template_args (args, extra_args);
573 
574   /* Now, we restore ARGS to its full dimensions.  */
575   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
576 
577   return new_args;
578 }
579 
580 /* Return the N levels of innermost template arguments from the ARGS.  */
581 
582 tree
583 get_innermost_template_args (tree args, int n)
584 {
585   tree new_args;
586   int extra_levels;
587   int i;
588 
589   gcc_assert (n >= 0);
590 
591   /* If N is 1, just return the innermost set of template arguments.  */
592   if (n == 1)
593     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
594 
595   /* If we're not removing anything, just return the arguments we were
596      given.  */
597   extra_levels = TMPL_ARGS_DEPTH (args) - n;
598   gcc_assert (extra_levels >= 0);
599   if (extra_levels == 0)
600     return args;
601 
602   /* Make a new set of arguments, not containing the outer arguments.  */
603   new_args = make_tree_vec (n);
604   for (i = 1; i <= n; ++i)
605     SET_TMPL_ARGS_LEVEL (new_args, i,
606 			 TMPL_ARGS_LEVEL (args, i + extra_levels));
607 
608   return new_args;
609 }
610 
611 /* The inverse of get_innermost_template_args: Return all but the innermost
612    EXTRA_LEVELS levels of template arguments from the ARGS.  */
613 
614 static tree
615 strip_innermost_template_args (tree args, int extra_levels)
616 {
617   tree new_args;
618   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
619   int i;
620 
621   gcc_assert (n >= 0);
622 
623   /* If N is 1, just return the outermost set of template arguments.  */
624   if (n == 1)
625     return TMPL_ARGS_LEVEL (args, 1);
626 
627   /* If we're not removing anything, just return the arguments we were
628      given.  */
629   gcc_assert (extra_levels >= 0);
630   if (extra_levels == 0)
631     return args;
632 
633   /* Make a new set of arguments, not containing the inner arguments.  */
634   new_args = make_tree_vec (n);
635   for (i = 1; i <= n; ++i)
636     SET_TMPL_ARGS_LEVEL (new_args, i,
637 			 TMPL_ARGS_LEVEL (args, i));
638 
639   return new_args;
640 }
641 
642 /* We've got a template header coming up; push to a new level for storing
643    the parms.  */
644 
645 void
646 begin_template_parm_list (void)
647 {
648   /* We use a non-tag-transparent scope here, which causes pushtag to
649      put tags in this scope, rather than in the enclosing class or
650      namespace scope.  This is the right thing, since we want
651      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
652      global template class, push_template_decl handles putting the
653      TEMPLATE_DECL into top-level scope.  For a nested template class,
654      e.g.:
655 
656        template <class T> struct S1 {
657 	 template <class T> struct S2 {};
658        };
659 
660      pushtag contains special code to insert the TEMPLATE_DECL for S2
661      at the right scope.  */
662   begin_scope (sk_template_parms, NULL);
663   ++processing_template_decl;
664   ++processing_template_parmlist;
665   note_template_header (0);
666 
667   /* Add a dummy parameter level while we process the parameter list.  */
668   current_template_parms
669     = tree_cons (size_int (processing_template_decl),
670 		 make_tree_vec (0),
671 		 current_template_parms);
672 }
673 
674 /* This routine is called when a specialization is declared.  If it is
675    invalid to declare a specialization here, an error is reported and
676    false is returned, otherwise this routine will return true.  */
677 
678 static bool
679 check_specialization_scope (void)
680 {
681   tree scope = current_scope ();
682 
683   /* [temp.expl.spec]
684 
685      An explicit specialization shall be declared in the namespace of
686      which the template is a member, or, for member templates, in the
687      namespace of which the enclosing class or enclosing class
688      template is a member.  An explicit specialization of a member
689      function, member class or static data member of a class template
690      shall be declared in the namespace of which the class template
691      is a member.  */
692   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
693     {
694       error ("explicit specialization in non-namespace scope %qD", scope);
695       return false;
696     }
697 
698   /* [temp.expl.spec]
699 
700      In an explicit specialization declaration for a member of a class
701      template or a member template that appears in namespace scope,
702      the member template and some of its enclosing class templates may
703      remain unspecialized, except that the declaration shall not
704      explicitly specialize a class member template if its enclosing
705      class templates are not explicitly specialized as well.  */
706   if (current_template_parms)
707     {
708       error ("enclosing class templates are not explicitly specialized");
709       return false;
710     }
711 
712   return true;
713 }
714 
715 /* We've just seen template <>.  */
716 
717 bool
718 begin_specialization (void)
719 {
720   begin_scope (sk_template_spec, NULL);
721   note_template_header (1);
722   return check_specialization_scope ();
723 }
724 
725 /* Called at then end of processing a declaration preceded by
726    template<>.  */
727 
728 void
729 end_specialization (void)
730 {
731   finish_scope ();
732   reset_specialization ();
733 }
734 
735 /* Any template <>'s that we have seen thus far are not referring to a
736    function specialization.  */
737 
738 void
739 reset_specialization (void)
740 {
741   processing_specialization = 0;
742   template_header_count = 0;
743 }
744 
745 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
746    it was of the form template <>.  */
747 
748 static void
749 note_template_header (int specialization)
750 {
751   processing_specialization = specialization;
752   template_header_count++;
753 }
754 
755 /* We're beginning an explicit instantiation.  */
756 
757 void
758 begin_explicit_instantiation (void)
759 {
760   gcc_assert (!processing_explicit_instantiation);
761   processing_explicit_instantiation = true;
762 }
763 
764 
765 void
766 end_explicit_instantiation (void)
767 {
768   gcc_assert (processing_explicit_instantiation);
769   processing_explicit_instantiation = false;
770 }
771 
772 /* An explicit specialization or partial specialization of TMPL is being
773    declared.  Check that the namespace in which the specialization is
774    occurring is permissible.  Returns false iff it is invalid to
775    specialize TMPL in the current namespace.  */
776 
777 static bool
778 check_specialization_namespace (tree tmpl)
779 {
780   tree tpl_ns = decl_namespace_context (tmpl);
781 
782   /* [tmpl.expl.spec]
783 
784      An explicit specialization shall be declared in a namespace enclosing the
785      specialized template. An explicit specialization whose declarator-id is
786      not qualified shall be declared in the nearest enclosing namespace of the
787      template, or, if the namespace is inline (7.3.1), any namespace from its
788      enclosing namespace set.  */
789   if (current_scope() != DECL_CONTEXT (tmpl)
790       && !at_namespace_scope_p ())
791     {
792       error ("specialization of %qD must appear at namespace scope", tmpl);
793       return false;
794     }
795 
796   if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
797     /* Same or enclosing namespace.  */
798     return true;
799   else
800     {
801       permerror (input_location,
802 		 "specialization of %qD in different namespace", tmpl);
803       inform (DECL_SOURCE_LOCATION (tmpl),
804 	      "  from definition of %q#D", tmpl);
805       return false;
806     }
807 }
808 
809 /* SPEC is an explicit instantiation.  Check that it is valid to
810    perform this explicit instantiation in the current namespace.  */
811 
812 static void
813 check_explicit_instantiation_namespace (tree spec)
814 {
815   tree ns;
816 
817   /* DR 275: An explicit instantiation shall appear in an enclosing
818      namespace of its template.  */
819   ns = decl_namespace_context (spec);
820   if (!is_nested_namespace (current_namespace, ns))
821     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
822 	       "(which does not enclose namespace %qD)",
823 	       spec, current_namespace, ns);
824 }
825 
826 // Returns the type of a template specialization only if that
827 // specialization needs to be defined. Otherwise (e.g., if the type has
828 // already been defined), the function returns NULL_TREE.
829 static tree
830 maybe_new_partial_specialization (tree type)
831 {
832   // An implicit instantiation of an incomplete type implies
833   // the definition of a new class template.
834   //
835   //    template<typename T>
836   //      struct S;
837   //
838   //    template<typename T>
839   //      struct S<T*>;
840   //
841   // Here, S<T*> is an implicit instantiation of S whose type
842   // is incomplete.
843   if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
844     return type;
845 
846   // It can also be the case that TYPE is a completed specialization.
847   // Continuing the previous example, suppose we also declare:
848   //
849   //    template<typename T>
850   //      requires Integral<T>
851   //        struct S<T*>;
852   //
853   // Here, S<T*> refers to the specialization S<T*> defined
854   // above. However, we need to differentiate definitions because
855   // we intend to define a new partial specialization. In this case,
856   // we rely on the fact that the constraints are different for
857   // this declaration than that above.
858   //
859   // Note that we also get here for injected class names and
860   // late-parsed template definitions. We must ensure that we
861   // do not create new type declarations for those cases.
862   if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
863     {
864       tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
865       tree args = CLASSTYPE_TI_ARGS (type);
866 
867       // If there are no template parameters, this cannot be a new
868       // partial template specializtion?
869       if (!current_template_parms)
870         return NULL_TREE;
871 
872       // The injected-class-name is not a new partial specialization.
873       if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
874 	return NULL_TREE;
875 
876       // If the constraints are not the same as those of the primary
877       // then, we can probably create a new specialization.
878       tree type_constr = current_template_constraints ();
879 
880       if (type == TREE_TYPE (tmpl))
881 	{
882 	  tree main_constr = get_constraints (tmpl);
883 	  if (equivalent_constraints (type_constr, main_constr))
884 	    return NULL_TREE;
885 	}
886 
887       // Also, if there's a pre-existing specialization with matching
888       // constraints, then this also isn't new.
889       tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
890       while (specs)
891         {
892           tree spec_tmpl = TREE_VALUE (specs);
893           tree spec_args = TREE_PURPOSE (specs);
894           tree spec_constr = get_constraints (spec_tmpl);
895           if (comp_template_args (args, spec_args)
896 	      && equivalent_constraints (type_constr, spec_constr))
897             return NULL_TREE;
898           specs = TREE_CHAIN (specs);
899         }
900 
901       // Create a new type node (and corresponding type decl)
902       // for the newly declared specialization.
903       tree t = make_class_type (TREE_CODE (type));
904       CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
905       SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
906 
907       /* We only need a separate type node for storing the definition of this
908 	 partial specialization; uses of S<T*> are unconstrained, so all are
909 	 equivalent.  So keep TYPE_CANONICAL the same.  */
910       TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
911 
912       // Build the corresponding type decl.
913       tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
914       DECL_CONTEXT (d) = TYPE_CONTEXT (t);
915       DECL_SOURCE_LOCATION (d) = input_location;
916 
917       return t;
918     }
919 
920   return NULL_TREE;
921 }
922 
923 /* The TYPE is being declared.  If it is a template type, that means it
924    is a partial specialization.  Do appropriate error-checking.  */
925 
926 tree
927 maybe_process_partial_specialization (tree type)
928 {
929   tree context;
930 
931   if (type == error_mark_node)
932     return error_mark_node;
933 
934   /* A lambda that appears in specialization context is not itself a
935      specialization.  */
936   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
937     return type;
938 
939   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
940     {
941       error ("name of class shadows template template parameter %qD",
942 	     TYPE_NAME (type));
943       return error_mark_node;
944     }
945 
946   context = TYPE_CONTEXT (type);
947 
948   if (TYPE_ALIAS_P (type))
949     {
950       tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
951 
952       if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
953 	error ("specialization of alias template %qD",
954 	       TI_TEMPLATE (tinfo));
955       else
956 	error ("explicit specialization of non-template %qT", type);
957       return error_mark_node;
958     }
959   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
960     {
961       /* This is for ordinary explicit specialization and partial
962 	 specialization of a template class such as:
963 
964 	   template <> class C<int>;
965 
966 	 or:
967 
968 	   template <class T> class C<T*>;
969 
970 	 Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
971 
972       if (tree t = maybe_new_partial_specialization (type))
973 	{
974 	  if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (t))
975 	      && !at_namespace_scope_p ())
976 	    return error_mark_node;
977 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (t);
978 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (t)) = input_location;
979 	  if (processing_template_decl)
980 	    {
981 	      tree decl = push_template_decl (TYPE_MAIN_DECL (t));
982 	      if (decl == error_mark_node)
983 		return error_mark_node;
984 	      return TREE_TYPE (decl);
985 	    }
986 	}
987       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
988 	error ("specialization of %qT after instantiation", type);
989       else if (errorcount && !processing_specialization
990 	        && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
991 	       && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
992 	/* Trying to define a specialization either without a template<> header
993 	   or in an inappropriate place.  We've already given an error, so just
994 	   bail now so we don't actually define the specialization.  */
995 	return error_mark_node;
996     }
997   else if (CLASS_TYPE_P (type)
998 	   && !CLASSTYPE_USE_TEMPLATE (type)
999 	   && CLASSTYPE_TEMPLATE_INFO (type)
1000 	   && context && CLASS_TYPE_P (context)
1001 	   && CLASSTYPE_TEMPLATE_INFO (context))
1002     {
1003       /* This is for an explicit specialization of member class
1004 	 template according to [temp.expl.spec/18]:
1005 
1006 	   template <> template <class U> class C<int>::D;
1007 
1008 	 The context `C<int>' must be an implicit instantiation.
1009 	 Otherwise this is just a member class template declared
1010 	 earlier like:
1011 
1012 	   template <> class C<int> { template <class U> class D; };
1013 	   template <> template <class U> class C<int>::D;
1014 
1015 	 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1016 	 while in the second case, `C<int>::D' is a primary template
1017 	 and `C<T>::D' may not exist.  */
1018 
1019       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1020 	  && !COMPLETE_TYPE_P (type))
1021 	{
1022 	  tree t;
1023 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1024 
1025 	  if (current_namespace
1026 	      != decl_namespace_context (tmpl))
1027 	    {
1028 	      permerror (input_location,
1029 			 "specializing %q#T in different namespace", type);
1030 	      permerror (DECL_SOURCE_LOCATION (tmpl),
1031 			 "  from definition of %q#D", tmpl);
1032 	    }
1033 
1034 	  /* Check for invalid specialization after instantiation:
1035 
1036 	       template <> template <> class C<int>::D<int>;
1037 	       template <> template <class U> class C<int>::D;  */
1038 
1039 	  for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1040 	       t; t = TREE_CHAIN (t))
1041 	    {
1042 	      tree inst = TREE_VALUE (t);
1043 	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1044 		  || !COMPLETE_OR_OPEN_TYPE_P (inst))
1045 		{
1046 		  /* We already have a full specialization of this partial
1047 		     instantiation, or a full specialization has been
1048 		     looked up but not instantiated.  Reassign it to the
1049 		     new member specialization template.  */
1050 		  spec_entry elt;
1051 		  spec_entry *entry;
1052 
1053 		  elt.tmpl = most_general_template (tmpl);
1054 		  elt.args = CLASSTYPE_TI_ARGS (inst);
1055 		  elt.spec = inst;
1056 
1057 		  type_specializations->remove_elt (&elt);
1058 
1059 		  elt.tmpl = tmpl;
1060 		  elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1061 
1062 		  spec_entry **slot
1063 		    = type_specializations->find_slot (&elt, INSERT);
1064 		  entry = ggc_alloc<spec_entry> ();
1065 		  *entry = elt;
1066 		  *slot = entry;
1067 		}
1068 	      else
1069 		/* But if we've had an implicit instantiation, that's a
1070 		   problem ([temp.expl.spec]/6).  */
1071 		error ("specialization %qT after instantiation %qT",
1072 		       type, inst);
1073 	    }
1074 
1075 	  /* Mark TYPE as a specialization.  And as a result, we only
1076 	     have one level of template argument for the innermost
1077 	     class template.  */
1078 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1079 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1080 	  CLASSTYPE_TI_ARGS (type)
1081 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1082 	}
1083     }
1084   else if (processing_specialization)
1085     {
1086        /* Someday C++0x may allow for enum template specialization.  */
1087       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1088 	  && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1089 	pedwarn (input_location, OPT_Wpedantic, "template specialization "
1090 		 "of %qD not allowed by ISO C++", type);
1091       else
1092 	{
1093 	  error ("explicit specialization of non-template %qT", type);
1094 	  return error_mark_node;
1095 	}
1096     }
1097 
1098   return type;
1099 }
1100 
1101 /* Returns nonzero if we can optimize the retrieval of specializations
1102    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
1103    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
1104 
1105 static inline bool
1106 optimize_specialization_lookup_p (tree tmpl)
1107 {
1108   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1109 	  && DECL_CLASS_SCOPE_P (tmpl)
1110 	  /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1111 	     parameter.  */
1112 	  && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1113 	  /* The optimized lookup depends on the fact that the
1114 	     template arguments for the member function template apply
1115 	     purely to the containing class, which is not true if the
1116 	     containing class is an explicit or partial
1117 	     specialization.  */
1118 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1119 	  && !DECL_MEMBER_TEMPLATE_P (tmpl)
1120 	  && !DECL_CONV_FN_P (tmpl)
1121 	  /* It is possible to have a template that is not a member
1122 	     template and is not a member of a template class:
1123 
1124 	     template <typename T>
1125 	     struct S { friend A::f(); };
1126 
1127 	     Here, the friend function is a template, but the context does
1128 	     not have template information.  The optimized lookup relies
1129 	     on having ARGS be the template arguments for both the class
1130 	     and the function template.  */
1131 	  && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1132 }
1133 
1134 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1135    gone through coerce_template_parms by now.  */
1136 
1137 static void
1138 verify_unstripped_args_1 (tree inner)
1139 {
1140   for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1141     {
1142       tree arg = TREE_VEC_ELT (inner, i);
1143       if (TREE_CODE (arg) == TEMPLATE_DECL)
1144 	/* OK */;
1145       else if (TYPE_P (arg))
1146 	gcc_assert (strip_typedefs (arg, NULL) == arg);
1147       else if (ARGUMENT_PACK_P (arg))
1148 	verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1149       else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1150 	/* Allow typedefs on the type of a non-type argument, since a
1151 	   parameter can have them.  */;
1152       else
1153 	gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1154     }
1155 }
1156 
1157 static void
1158 verify_unstripped_args (tree args)
1159 {
1160   ++processing_template_decl;
1161   if (!any_dependent_template_arguments_p (args))
1162     verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1163   --processing_template_decl;
1164 }
1165 
1166 /* Retrieve the specialization (in the sense of [temp.spec] - a
1167    specialization is either an instantiation or an explicit
1168    specialization) of TMPL for the given template ARGS.  If there is
1169    no such specialization, return NULL_TREE.  The ARGS are a vector of
1170    arguments, or a vector of vectors of arguments, in the case of
1171    templates with more than one level of parameters.
1172 
1173    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1174    then we search for a partial specialization matching ARGS.  This
1175    parameter is ignored if TMPL is not a class template.
1176 
1177    We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1178    result is a NONTYPE_ARGUMENT_PACK.  */
1179 
1180 static tree
1181 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1182 {
1183   if (tmpl == NULL_TREE)
1184     return NULL_TREE;
1185 
1186   if (args == error_mark_node)
1187     return NULL_TREE;
1188 
1189   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1190 	      || TREE_CODE (tmpl) == FIELD_DECL);
1191 
1192   /* There should be as many levels of arguments as there are
1193      levels of parameters.  */
1194   gcc_assert (TMPL_ARGS_DEPTH (args)
1195 	      == (TREE_CODE (tmpl) == TEMPLATE_DECL
1196 		  ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1197 		  : template_class_depth (DECL_CONTEXT (tmpl))));
1198 
1199   if (flag_checking)
1200     verify_unstripped_args (args);
1201 
1202   /* Lambda functions in templates aren't instantiated normally, but through
1203      tsubst_lambda_expr.  */
1204   if (lambda_fn_in_template_p (tmpl))
1205     return NULL_TREE;
1206 
1207   if (optimize_specialization_lookup_p (tmpl))
1208     {
1209       /* The template arguments actually apply to the containing
1210 	 class.  Find the class specialization with those
1211 	 arguments.  */
1212       tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1213       tree class_specialization
1214 	= retrieve_specialization (class_template, args, 0);
1215       if (!class_specialization)
1216 	return NULL_TREE;
1217 
1218       /* Find the instance of TMPL.  */
1219       tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1220       for (ovl_iterator iter (fns); iter; ++iter)
1221 	{
1222 	  tree fn = *iter;
1223 	  if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1224 	      /* using-declarations can add base methods to the method vec,
1225 		 and we don't want those here.  */
1226 	      && DECL_CONTEXT (fn) == class_specialization)
1227 	    return fn;
1228 	}
1229       return NULL_TREE;
1230     }
1231   else
1232     {
1233       spec_entry *found;
1234       spec_entry elt;
1235       hash_table<spec_hasher> *specializations;
1236 
1237       elt.tmpl = tmpl;
1238       elt.args = args;
1239       elt.spec = NULL_TREE;
1240 
1241       if (DECL_CLASS_TEMPLATE_P (tmpl))
1242 	specializations = type_specializations;
1243       else
1244 	specializations = decl_specializations;
1245 
1246       if (hash == 0)
1247 	hash = spec_hasher::hash (&elt);
1248       found = specializations->find_with_hash (&elt, hash);
1249       if (found)
1250 	return found->spec;
1251     }
1252 
1253   return NULL_TREE;
1254 }
1255 
1256 /* Like retrieve_specialization, but for local declarations.  */
1257 
1258 tree
1259 retrieve_local_specialization (tree tmpl)
1260 {
1261   if (local_specializations == NULL)
1262     return NULL_TREE;
1263 
1264   tree *slot = local_specializations->get (tmpl);
1265   return slot ? *slot : NULL_TREE;
1266 }
1267 
1268 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1269 
1270 int
1271 is_specialization_of (tree decl, tree tmpl)
1272 {
1273   tree t;
1274 
1275   if (TREE_CODE (decl) == FUNCTION_DECL)
1276     {
1277       for (t = decl;
1278 	   t != NULL_TREE;
1279 	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1280 	if (t == tmpl)
1281 	  return 1;
1282     }
1283   else
1284     {
1285       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1286 
1287       for (t = TREE_TYPE (decl);
1288 	   t != NULL_TREE;
1289 	   t = CLASSTYPE_USE_TEMPLATE (t)
1290 	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1291 	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1292 	  return 1;
1293     }
1294 
1295   return 0;
1296 }
1297 
1298 /* Returns nonzero iff DECL is a specialization of friend declaration
1299    FRIEND_DECL according to [temp.friend].  */
1300 
1301 bool
1302 is_specialization_of_friend (tree decl, tree friend_decl)
1303 {
1304   bool need_template = true;
1305   int template_depth;
1306 
1307   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1308 	      || TREE_CODE (decl) == TYPE_DECL);
1309 
1310   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1311      of a template class, we want to check if DECL is a specialization
1312      if this.  */
1313   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1314       && DECL_TEMPLATE_INFO (friend_decl)
1315       && !DECL_USE_TEMPLATE (friend_decl))
1316     {
1317       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1318       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1319       need_template = false;
1320     }
1321   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1322 	   && !PRIMARY_TEMPLATE_P (friend_decl))
1323     need_template = false;
1324 
1325   /* There is nothing to do if this is not a template friend.  */
1326   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1327     return false;
1328 
1329   if (is_specialization_of (decl, friend_decl))
1330     return true;
1331 
1332   /* [temp.friend/6]
1333      A member of a class template may be declared to be a friend of a
1334      non-template class.  In this case, the corresponding member of
1335      every specialization of the class template is a friend of the
1336      class granting friendship.
1337 
1338      For example, given a template friend declaration
1339 
1340        template <class T> friend void A<T>::f();
1341 
1342      the member function below is considered a friend
1343 
1344        template <> struct A<int> {
1345 	 void f();
1346        };
1347 
1348      For this type of template friend, TEMPLATE_DEPTH below will be
1349      nonzero.  To determine if DECL is a friend of FRIEND, we first
1350      check if the enclosing class is a specialization of another.  */
1351 
1352   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1353   if (template_depth
1354       && DECL_CLASS_SCOPE_P (decl)
1355       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1356 			       CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1357     {
1358       /* Next, we check the members themselves.  In order to handle
1359 	 a few tricky cases, such as when FRIEND_DECL's are
1360 
1361 	   template <class T> friend void A<T>::g(T t);
1362 	   template <class T> template <T t> friend void A<T>::h();
1363 
1364 	 and DECL's are
1365 
1366 	   void A<int>::g(int);
1367 	   template <int> void A<int>::h();
1368 
1369 	 we need to figure out ARGS, the template arguments from
1370 	 the context of DECL.  This is required for template substitution
1371 	 of `T' in the function parameter of `g' and template parameter
1372 	 of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1373 
1374       tree context = DECL_CONTEXT (decl);
1375       tree args = NULL_TREE;
1376       int current_depth = 0;
1377 
1378       while (current_depth < template_depth)
1379 	{
1380 	  if (CLASSTYPE_TEMPLATE_INFO (context))
1381 	    {
1382 	      if (current_depth == 0)
1383 		args = TYPE_TI_ARGS (context);
1384 	      else
1385 		args = add_to_template_args (TYPE_TI_ARGS (context), args);
1386 	      current_depth++;
1387 	    }
1388 	  context = TYPE_CONTEXT (context);
1389 	}
1390 
1391       if (TREE_CODE (decl) == FUNCTION_DECL)
1392 	{
1393 	  bool is_template;
1394 	  tree friend_type;
1395 	  tree decl_type;
1396 	  tree friend_args_type;
1397 	  tree decl_args_type;
1398 
1399 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1400 	     non-templates.  */
1401 	  is_template = DECL_TEMPLATE_INFO (decl)
1402 			&& PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1403 	  if (need_template ^ is_template)
1404 	    return false;
1405 	  else if (is_template)
1406 	    {
1407 	      /* If both are templates, check template parameter list.  */
1408 	      tree friend_parms
1409 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1410 					 args, tf_none);
1411 	      if (!comp_template_parms
1412 		     (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1413 		      friend_parms))
1414 		return false;
1415 
1416 	      decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1417 	    }
1418 	  else
1419 	    decl_type = TREE_TYPE (decl);
1420 
1421 	  friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1422 					      tf_none, NULL_TREE);
1423 	  if (friend_type == error_mark_node)
1424 	    return false;
1425 
1426 	  /* Check if return types match.  */
1427 	  if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1428 	    return false;
1429 
1430 	  /* Check if function parameter types match, ignoring the
1431 	     `this' parameter.  */
1432 	  friend_args_type = TYPE_ARG_TYPES (friend_type);
1433 	  decl_args_type = TYPE_ARG_TYPES (decl_type);
1434 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1435 	    friend_args_type = TREE_CHAIN (friend_args_type);
1436 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1437 	    decl_args_type = TREE_CHAIN (decl_args_type);
1438 
1439 	  return compparms (decl_args_type, friend_args_type);
1440 	}
1441       else
1442 	{
1443 	  /* DECL is a TYPE_DECL */
1444 	  bool is_template;
1445 	  tree decl_type = TREE_TYPE (decl);
1446 
1447 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1448 	     non-templates.  */
1449 	  is_template
1450 	    = CLASSTYPE_TEMPLATE_INFO (decl_type)
1451 	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1452 
1453 	  if (need_template ^ is_template)
1454 	    return false;
1455 	  else if (is_template)
1456 	    {
1457 	      tree friend_parms;
1458 	      /* If both are templates, check the name of the two
1459 		 TEMPLATE_DECL's first because is_friend didn't.  */
1460 	      if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1461 		  != DECL_NAME (friend_decl))
1462 		return false;
1463 
1464 	      /* Now check template parameter list.  */
1465 	      friend_parms
1466 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1467 					 args, tf_none);
1468 	      return comp_template_parms
1469 		(DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1470 		 friend_parms);
1471 	    }
1472 	  else
1473 	    return (DECL_NAME (decl)
1474 		    == DECL_NAME (friend_decl));
1475 	}
1476     }
1477   return false;
1478 }
1479 
1480 /* Register the specialization SPEC as a specialization of TMPL with
1481    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1482    is actually just a friend declaration.  ATTRLIST is the list of
1483    attributes that the specialization is declared with or NULL when
1484    it isn't.  Returns SPEC, or an equivalent prior declaration, if
1485    available.
1486 
1487    We also store instantiations of field packs in the hash table, even
1488    though they are not themselves templates, to make lookup easier.  */
1489 
1490 static tree
1491 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1492 			 hashval_t hash)
1493 {
1494   tree fn;
1495   spec_entry **slot = NULL;
1496   spec_entry elt;
1497 
1498   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1499 	      || (TREE_CODE (tmpl) == FIELD_DECL
1500 		  && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1501 
1502   if (TREE_CODE (spec) == FUNCTION_DECL
1503       && uses_template_parms (DECL_TI_ARGS (spec)))
1504     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1505        register it; we want the corresponding TEMPLATE_DECL instead.
1506        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1507        the more obvious `uses_template_parms (spec)' to avoid problems
1508        with default function arguments.  In particular, given
1509        something like this:
1510 
1511 	  template <class T> void f(T t1, T t = T())
1512 
1513        the default argument expression is not substituted for in an
1514        instantiation unless and until it is actually needed.  */
1515     return spec;
1516 
1517   if (optimize_specialization_lookup_p (tmpl))
1518     /* We don't put these specializations in the hash table, but we might
1519        want to give an error about a mismatch.  */
1520     fn = retrieve_specialization (tmpl, args, 0);
1521   else
1522     {
1523       elt.tmpl = tmpl;
1524       elt.args = args;
1525       elt.spec = spec;
1526 
1527       if (hash == 0)
1528 	hash = spec_hasher::hash (&elt);
1529 
1530       slot =
1531 	decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1532       if (*slot)
1533 	fn = ((spec_entry *) *slot)->spec;
1534       else
1535 	fn = NULL_TREE;
1536     }
1537 
1538   /* We can sometimes try to re-register a specialization that we've
1539      already got.  In particular, regenerate_decl_from_template calls
1540      duplicate_decls which will update the specialization list.  But,
1541      we'll still get called again here anyhow.  It's more convenient
1542      to simply allow this than to try to prevent it.  */
1543   if (fn == spec)
1544     return spec;
1545   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1546     {
1547       if (DECL_TEMPLATE_INSTANTIATION (fn))
1548 	{
1549 	  if (DECL_ODR_USED (fn)
1550 	      || DECL_EXPLICIT_INSTANTIATION (fn))
1551 	    {
1552 	      error ("specialization of %qD after instantiation",
1553 		     fn);
1554 	      return error_mark_node;
1555 	    }
1556 	  else
1557 	    {
1558 	      tree clone;
1559 	      /* This situation should occur only if the first
1560 		 specialization is an implicit instantiation, the
1561 		 second is an explicit specialization, and the
1562 		 implicit instantiation has not yet been used.  That
1563 		 situation can occur if we have implicitly
1564 		 instantiated a member function and then specialized
1565 		 it later.
1566 
1567 		 We can also wind up here if a friend declaration that
1568 		 looked like an instantiation turns out to be a
1569 		 specialization:
1570 
1571 		   template <class T> void foo(T);
1572 		   class S { friend void foo<>(int) };
1573 		   template <> void foo(int);
1574 
1575 		 We transform the existing DECL in place so that any
1576 		 pointers to it become pointers to the updated
1577 		 declaration.
1578 
1579 		 If there was a definition for the template, but not
1580 		 for the specialization, we want this to look as if
1581 		 there were no definition, and vice versa.  */
1582 	      DECL_INITIAL (fn) = NULL_TREE;
1583 	      duplicate_decls (spec, fn, is_friend);
1584 	      /* The call to duplicate_decls will have applied
1585 		 [temp.expl.spec]:
1586 
1587 		   An explicit specialization of a function template
1588 		   is inline only if it is explicitly declared to be,
1589 		   and independently of whether its function template
1590 		   is.
1591 
1592 		to the primary function; now copy the inline bits to
1593 		the various clones.  */
1594 	      FOR_EACH_CLONE (clone, fn)
1595 		{
1596 		  DECL_DECLARED_INLINE_P (clone)
1597 		    = DECL_DECLARED_INLINE_P (fn);
1598 		  DECL_SOURCE_LOCATION (clone)
1599 		    = DECL_SOURCE_LOCATION (fn);
1600 		  DECL_DELETED_FN (clone)
1601 		    = DECL_DELETED_FN (fn);
1602 		}
1603 	      check_specialization_namespace (tmpl);
1604 
1605 	      return fn;
1606 	    }
1607 	}
1608       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1609 	{
1610 	  tree dd = duplicate_decls (spec, fn, is_friend);
1611 	  if (dd == error_mark_node)
1612 	    /* We've already complained in duplicate_decls.  */
1613 	    return error_mark_node;
1614 
1615 	  if (dd == NULL_TREE && DECL_INITIAL (spec))
1616 	    /* Dup decl failed, but this is a new definition. Set the
1617 	       line number so any errors match this new
1618 	       definition.  */
1619 	    DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1620 
1621 	  return fn;
1622 	}
1623     }
1624   else if (fn)
1625     return duplicate_decls (spec, fn, is_friend);
1626 
1627   /* A specialization must be declared in the same namespace as the
1628      template it is specializing.  */
1629   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1630       && !check_specialization_namespace (tmpl))
1631     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1632 
1633   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1634     {
1635       spec_entry *entry = ggc_alloc<spec_entry> ();
1636       gcc_assert (tmpl && args && spec);
1637       *entry = elt;
1638       *slot = entry;
1639       if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1640 	   && PRIMARY_TEMPLATE_P (tmpl)
1641 	   && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1642 	  || variable_template_p (tmpl))
1643 	/* If TMPL is a forward declaration of a template function, keep a list
1644 	   of all specializations in case we need to reassign them to a friend
1645 	   template later in tsubst_friend_function.
1646 
1647 	   Also keep a list of all variable template instantiations so that
1648 	   process_partial_specialization can check whether a later partial
1649 	   specialization would have used it.  */
1650 	DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1651 	  = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1652     }
1653 
1654   return spec;
1655 }
1656 
1657 /* Returns true iff two spec_entry nodes are equivalent.  */
1658 
1659 int comparing_specializations;
1660 
1661 bool
1662 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1663 {
1664   int equal;
1665 
1666   ++comparing_specializations;
1667   equal = (e1->tmpl == e2->tmpl
1668 	   && comp_template_args (e1->args, e2->args));
1669   if (equal && flag_concepts
1670       /* tmpl could be a FIELD_DECL for a capture pack.  */
1671       && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1672       && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1673       && uses_template_parms (e1->args))
1674     {
1675       /* Partial specializations of a variable template can be distinguished by
1676 	 constraints.  */
1677       tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1678       tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1679       equal = equivalent_constraints (c1, c2);
1680     }
1681   --comparing_specializations;
1682 
1683   return equal;
1684 }
1685 
1686 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1687 
1688 static hashval_t
1689 hash_tmpl_and_args (tree tmpl, tree args)
1690 {
1691   hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1692   return iterative_hash_template_arg (args, val);
1693 }
1694 
1695 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1696    ignoring SPEC.  */
1697 
1698 hashval_t
1699 spec_hasher::hash (spec_entry *e)
1700 {
1701   return hash_tmpl_and_args (e->tmpl, e->args);
1702 }
1703 
1704 /* Recursively calculate a hash value for a template argument ARG, for use
1705    in the hash tables of template specializations.  */
1706 
1707 hashval_t
1708 iterative_hash_template_arg (tree arg, hashval_t val)
1709 {
1710   unsigned HOST_WIDE_INT i;
1711   enum tree_code code;
1712   char tclass;
1713 
1714   if (arg == NULL_TREE)
1715     return iterative_hash_object (arg, val);
1716 
1717   if (!TYPE_P (arg))
1718     STRIP_NOPS (arg);
1719 
1720   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1721     gcc_unreachable ();
1722 
1723   code = TREE_CODE (arg);
1724   tclass = TREE_CODE_CLASS (code);
1725 
1726   val = iterative_hash_object (code, val);
1727 
1728   switch (code)
1729     {
1730     case ERROR_MARK:
1731       return val;
1732 
1733     case IDENTIFIER_NODE:
1734       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1735 
1736     case TREE_VEC:
1737       {
1738 	int i, len = TREE_VEC_LENGTH (arg);
1739 	for (i = 0; i < len; ++i)
1740 	  val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1741 	return val;
1742       }
1743 
1744     case TYPE_PACK_EXPANSION:
1745     case EXPR_PACK_EXPANSION:
1746       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1747       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1748 
1749     case TYPE_ARGUMENT_PACK:
1750     case NONTYPE_ARGUMENT_PACK:
1751       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1752 
1753     case TREE_LIST:
1754       for (; arg; arg = TREE_CHAIN (arg))
1755 	val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1756       return val;
1757 
1758     case OVERLOAD:
1759       for (lkp_iterator iter (arg); iter; ++iter)
1760 	val = iterative_hash_template_arg (*iter, val);
1761       return val;
1762 
1763     case CONSTRUCTOR:
1764       {
1765 	tree field, value;
1766 	iterative_hash_template_arg (TREE_TYPE (arg), val);
1767 	FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1768 	  {
1769 	    val = iterative_hash_template_arg (field, val);
1770 	    val = iterative_hash_template_arg (value, val);
1771 	  }
1772 	return val;
1773       }
1774 
1775     case PARM_DECL:
1776       if (!DECL_ARTIFICIAL (arg))
1777 	{
1778 	  val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1779 	  val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1780 	}
1781       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1782 
1783     case TARGET_EXPR:
1784       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1785 
1786     case PTRMEM_CST:
1787       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1788       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1789 
1790     case TEMPLATE_PARM_INDEX:
1791       val = iterative_hash_template_arg
1792 	(TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1793       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1794       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1795 
1796     case TRAIT_EXPR:
1797       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1798       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1799       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1800 
1801     case BASELINK:
1802       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1803 					 val);
1804       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1805 					  val);
1806 
1807     case MODOP_EXPR:
1808       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1809       code = TREE_CODE (TREE_OPERAND (arg, 1));
1810       val = iterative_hash_object (code, val);
1811       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1812 
1813     case LAMBDA_EXPR:
1814       /* A lambda can't appear in a template arg, but don't crash on
1815 	 erroneous input.  */
1816       gcc_assert (seen_error ());
1817       return val;
1818 
1819     case CAST_EXPR:
1820     case IMPLICIT_CONV_EXPR:
1821     case STATIC_CAST_EXPR:
1822     case REINTERPRET_CAST_EXPR:
1823     case CONST_CAST_EXPR:
1824     case DYNAMIC_CAST_EXPR:
1825     case NEW_EXPR:
1826       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1827       /* Now hash operands as usual.  */
1828       break;
1829 
1830     default:
1831       break;
1832     }
1833 
1834   switch (tclass)
1835     {
1836     case tcc_type:
1837       if (alias_template_specialization_p (arg))
1838 	{
1839 	  // We want an alias specialization that survived strip_typedefs
1840 	  // to hash differently from its TYPE_CANONICAL, to avoid hash
1841 	  // collisions that compare as different in template_args_equal.
1842 	  // These could be dependent specializations that strip_typedefs
1843 	  // left alone, or untouched specializations because
1844 	  // coerce_template_parms returns the unconverted template
1845 	  // arguments if it sees incomplete argument packs.
1846 	  tree ti = TYPE_ALIAS_TEMPLATE_INFO (arg);
1847 	  return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1848 	}
1849       if (TYPE_CANONICAL (arg))
1850 	return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1851 				      val);
1852       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1853 	return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1854       /* Otherwise just compare the types during lookup.  */
1855       return val;
1856 
1857     case tcc_declaration:
1858     case tcc_constant:
1859       return iterative_hash_expr (arg, val);
1860 
1861     default:
1862       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1863       {
1864 	unsigned n = cp_tree_operand_length (arg);
1865 	for (i = 0; i < n; ++i)
1866 	  val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1867 	return val;
1868       }
1869     }
1870   gcc_unreachable ();
1871   return 0;
1872 }
1873 
1874 /* Unregister the specialization SPEC as a specialization of TMPL.
1875    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1876    if the SPEC was listed as a specialization of TMPL.
1877 
1878    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1879 
1880 bool
1881 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1882 {
1883   spec_entry *entry;
1884   spec_entry elt;
1885 
1886   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1887   elt.args = TI_ARGS (tinfo);
1888   elt.spec = NULL_TREE;
1889 
1890   entry = decl_specializations->find (&elt);
1891   if (entry != NULL)
1892     {
1893       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1894       gcc_assert (new_spec != NULL_TREE);
1895       entry->spec = new_spec;
1896       return 1;
1897     }
1898 
1899   return 0;
1900 }
1901 
1902 /* Like register_specialization, but for local declarations.  We are
1903    registering SPEC, an instantiation of TMPL.  */
1904 
1905 void
1906 register_local_specialization (tree spec, tree tmpl)
1907 {
1908   gcc_assert (tmpl != spec);
1909   local_specializations->put (tmpl, spec);
1910 }
1911 
1912 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1913    specialized class.  */
1914 
1915 bool
1916 explicit_class_specialization_p (tree type)
1917 {
1918   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1919     return false;
1920   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1921 }
1922 
1923 /* Print the list of functions at FNS, going through all the overloads
1924    for each element of the list.  Alternatively, FNS can not be a
1925    TREE_LIST, in which case it will be printed together with all the
1926    overloads.
1927 
1928    MORE and *STR should respectively be FALSE and NULL when the function
1929    is called from the outside.  They are used internally on recursive
1930    calls.  print_candidates manages the two parameters and leaves NULL
1931    in *STR when it ends.  */
1932 
1933 static void
1934 print_candidates_1 (tree fns, char **str, bool more = false)
1935 {
1936   if (TREE_CODE (fns) == TREE_LIST)
1937     for (; fns; fns = TREE_CHAIN (fns))
1938       print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
1939   else
1940     for (lkp_iterator iter (fns); iter;)
1941       {
1942 	tree cand = *iter;
1943 	++iter;
1944 
1945 	const char *pfx = *str;
1946 	if (!pfx)
1947 	  {
1948 	    if (more || iter)
1949 	      pfx = _("candidates are:");
1950 	    else
1951 	      pfx = _("candidate is:");
1952 	    *str = get_spaces (pfx);
1953 	  }
1954 	inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
1955       }
1956 }
1957 
1958 /* Print the list of candidate FNS in an error message.  FNS can also
1959    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1960 
1961 void
1962 print_candidates (tree fns)
1963 {
1964   char *str = NULL;
1965   print_candidates_1 (fns, &str);
1966   free (str);
1967 }
1968 
1969 /* Get a (possibly) constrained template declaration for the
1970    purpose of ordering candidates.  */
1971 static tree
1972 get_template_for_ordering (tree list)
1973 {
1974   gcc_assert (TREE_CODE (list) == TREE_LIST);
1975   tree f = TREE_VALUE (list);
1976   if (tree ti = DECL_TEMPLATE_INFO (f))
1977     return TI_TEMPLATE (ti);
1978   return f;
1979 }
1980 
1981 /* Among candidates having the same signature, return the
1982    most constrained or NULL_TREE if there is no best candidate.
1983    If the signatures of candidates vary (e.g., template
1984    specialization vs. member function), then there can be no
1985    most constrained.
1986 
1987    Note that we don't compare constraints on the functions
1988    themselves, but rather those of their templates. */
1989 static tree
1990 most_constrained_function (tree candidates)
1991 {
1992   // Try to find the best candidate in a first pass.
1993   tree champ = candidates;
1994   for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
1995     {
1996       int winner = more_constrained (get_template_for_ordering (champ),
1997                                      get_template_for_ordering (c));
1998       if (winner == -1)
1999         champ = c; // The candidate is more constrained
2000       else if (winner == 0)
2001         return NULL_TREE; // Neither is more constrained
2002     }
2003 
2004   // Verify that the champ is better than previous candidates.
2005   for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2006     if (!more_constrained (get_template_for_ordering (champ),
2007                            get_template_for_ordering (c)))
2008       return NULL_TREE;
2009   }
2010 
2011   return champ;
2012 }
2013 
2014 
2015 /* Returns the template (one of the functions given by TEMPLATE_ID)
2016    which can be specialized to match the indicated DECL with the
2017    explicit template args given in TEMPLATE_ID.  The DECL may be
2018    NULL_TREE if none is available.  In that case, the functions in
2019    TEMPLATE_ID are non-members.
2020 
2021    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2022    specialization of a member template.
2023 
2024    The TEMPLATE_COUNT is the number of references to qualifying
2025    template classes that appeared in the name of the function. See
2026    check_explicit_specialization for a more accurate description.
2027 
2028    TSK indicates what kind of template declaration (if any) is being
2029    declared.  TSK_TEMPLATE indicates that the declaration given by
2030    DECL, though a FUNCTION_DECL, has template parameters, and is
2031    therefore a template function.
2032 
2033    The template args (those explicitly specified and those deduced)
2034    are output in a newly created vector *TARGS_OUT.
2035 
2036    If it is impossible to determine the result, an error message is
2037    issued.  The error_mark_node is returned to indicate failure.  */
2038 
2039 static tree
2040 determine_specialization (tree template_id,
2041 			  tree decl,
2042 			  tree* targs_out,
2043 			  int need_member_template,
2044 			  int template_count,
2045 			  tmpl_spec_kind tsk)
2046 {
2047   tree fns;
2048   tree targs;
2049   tree explicit_targs;
2050   tree candidates = NULL_TREE;
2051 
2052   /* A TREE_LIST of templates of which DECL may be a specialization.
2053      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
2054      corresponding TREE_PURPOSE is the set of template arguments that,
2055      when used to instantiate the template, would produce a function
2056      with the signature of DECL.  */
2057   tree templates = NULL_TREE;
2058   int header_count;
2059   cp_binding_level *b;
2060 
2061   *targs_out = NULL_TREE;
2062 
2063   if (template_id == error_mark_node || decl == error_mark_node)
2064     return error_mark_node;
2065 
2066   /* We shouldn't be specializing a member template of an
2067      unspecialized class template; we already gave an error in
2068      check_specialization_scope, now avoid crashing.  */
2069   if (!VAR_P (decl)
2070       && template_count && DECL_CLASS_SCOPE_P (decl)
2071       && template_class_depth (DECL_CONTEXT (decl)) > 0)
2072     {
2073       gcc_assert (errorcount);
2074       return error_mark_node;
2075     }
2076 
2077   fns = TREE_OPERAND (template_id, 0);
2078   explicit_targs = TREE_OPERAND (template_id, 1);
2079 
2080   if (fns == error_mark_node)
2081     return error_mark_node;
2082 
2083   /* Check for baselinks.  */
2084   if (BASELINK_P (fns))
2085     fns = BASELINK_FUNCTIONS (fns);
2086 
2087   if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2088     {
2089       error ("%qD is not a function template", fns);
2090       return error_mark_node;
2091     }
2092   else if (VAR_P (decl) && !variable_template_p (fns))
2093     {
2094       error ("%qD is not a variable template", fns);
2095       return error_mark_node;
2096     }
2097 
2098   /* Count the number of template headers specified for this
2099      specialization.  */
2100   header_count = 0;
2101   for (b = current_binding_level;
2102        b->kind == sk_template_parms;
2103        b = b->level_chain)
2104     ++header_count;
2105 
2106   tree orig_fns = fns;
2107 
2108   if (variable_template_p (fns))
2109     {
2110       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2111       targs = coerce_template_parms (parms, explicit_targs, fns,
2112 				     tf_warning_or_error,
2113 				     /*req_all*/true, /*use_defarg*/true);
2114       if (targs != error_mark_node)
2115         templates = tree_cons (targs, fns, templates);
2116     }
2117   else for (lkp_iterator iter (fns); iter; ++iter)
2118     {
2119       tree fn = *iter;
2120 
2121       if (TREE_CODE (fn) == TEMPLATE_DECL)
2122 	{
2123 	  tree decl_arg_types;
2124 	  tree fn_arg_types;
2125 	  tree insttype;
2126 
2127 	  /* In case of explicit specialization, we need to check if
2128 	     the number of template headers appearing in the specialization
2129 	     is correct. This is usually done in check_explicit_specialization,
2130 	     but the check done there cannot be exhaustive when specializing
2131 	     member functions. Consider the following code:
2132 
2133 	     template <> void A<int>::f(int);
2134 	     template <> template <> void A<int>::f(int);
2135 
2136 	     Assuming that A<int> is not itself an explicit specialization
2137 	     already, the first line specializes "f" which is a non-template
2138 	     member function, whilst the second line specializes "f" which
2139 	     is a template member function. So both lines are syntactically
2140 	     correct, and check_explicit_specialization does not reject
2141 	     them.
2142 
2143 	     Here, we can do better, as we are matching the specialization
2144 	     against the declarations. We count the number of template
2145 	     headers, and we check if they match TEMPLATE_COUNT + 1
2146 	     (TEMPLATE_COUNT is the number of qualifying template classes,
2147 	     plus there must be another header for the member template
2148 	     itself).
2149 
2150 	     Notice that if header_count is zero, this is not a
2151 	     specialization but rather a template instantiation, so there
2152 	     is no check we can perform here.  */
2153 	  if (header_count && header_count != template_count + 1)
2154 	    continue;
2155 
2156 	  /* Check that the number of template arguments at the
2157 	     innermost level for DECL is the same as for FN.  */
2158 	  if (current_binding_level->kind == sk_template_parms
2159 	      && !current_binding_level->explicit_spec_p
2160 	      && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2161 		  != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2162 				      (current_template_parms))))
2163 	    continue;
2164 
2165 	  /* DECL might be a specialization of FN.  */
2166 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2167 	  fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2168 
2169 	  /* For a non-static member function, we need to make sure
2170 	     that the const qualification is the same.  Since
2171 	     get_bindings does not try to merge the "this" parameter,
2172 	     we must do the comparison explicitly.  */
2173 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2174 	    {
2175 	      if (!same_type_p (TREE_VALUE (fn_arg_types),
2176 				TREE_VALUE (decl_arg_types)))
2177 		continue;
2178 
2179 	      /* And the ref-qualification.  */
2180 	      if (type_memfn_rqual (TREE_TYPE (decl))
2181 		  != type_memfn_rqual (TREE_TYPE (fn)))
2182 		continue;
2183 	    }
2184 
2185 	  /* Skip the "this" parameter and, for constructors of
2186 	     classes with virtual bases, the VTT parameter.  A
2187 	     full specialization of a constructor will have a VTT
2188 	     parameter, but a template never will.  */
2189 	  decl_arg_types
2190 	    = skip_artificial_parms_for (decl, decl_arg_types);
2191 	  fn_arg_types
2192 	    = skip_artificial_parms_for (fn, fn_arg_types);
2193 
2194 	  /* Function templates cannot be specializations; there are
2195 	     no partial specializations of functions.  Therefore, if
2196 	     the type of DECL does not match FN, there is no
2197 	     match.
2198 
2199              Note that it should never be the case that we have both
2200              candidates added here, and for regular member functions
2201              below. */
2202 	  if (tsk == tsk_template)
2203 	    {
2204 	      if (compparms (fn_arg_types, decl_arg_types))
2205 		candidates = tree_cons (NULL_TREE, fn, candidates);
2206 	      continue;
2207 	    }
2208 
2209 	  /* See whether this function might be a specialization of this
2210 	     template.  Suppress access control because we might be trying
2211 	     to make this specialization a friend, and we have already done
2212 	     access control for the declaration of the specialization.  */
2213 	  push_deferring_access_checks (dk_no_check);
2214 	  targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2215 	  pop_deferring_access_checks ();
2216 
2217 	  if (!targs)
2218 	    /* We cannot deduce template arguments that when used to
2219 	       specialize TMPL will produce DECL.  */
2220 	    continue;
2221 
2222 	  if (uses_template_parms (targs))
2223 	    /* We deduced something involving 'auto', which isn't a valid
2224 	       template argument.  */
2225 	    continue;
2226 
2227           /* Remove, from the set of candidates, all those functions
2228              whose constraints are not satisfied. */
2229           if (flag_concepts && !constraints_satisfied_p (fn, targs))
2230             continue;
2231 
2232           // Then, try to form the new function type.
2233 	  insttype = tsubst (TREE_TYPE (fn), targs, tf_fndecl_type, NULL_TREE);
2234 	  if (insttype == error_mark_node)
2235 	    continue;
2236 	  fn_arg_types
2237 	    = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2238 	  if (!compparms (fn_arg_types, decl_arg_types))
2239 	    continue;
2240 
2241 	  /* Save this template, and the arguments deduced.  */
2242 	  templates = tree_cons (targs, fn, templates);
2243 	}
2244       else if (need_member_template)
2245 	/* FN is an ordinary member function, and we need a
2246 	   specialization of a member template.  */
2247 	;
2248       else if (TREE_CODE (fn) != FUNCTION_DECL)
2249 	/* We can get IDENTIFIER_NODEs here in certain erroneous
2250 	   cases.  */
2251 	;
2252       else if (!DECL_FUNCTION_MEMBER_P (fn))
2253 	/* This is just an ordinary non-member function.  Nothing can
2254 	   be a specialization of that.  */
2255 	;
2256       else if (DECL_ARTIFICIAL (fn))
2257 	/* Cannot specialize functions that are created implicitly.  */
2258 	;
2259       else
2260 	{
2261 	  tree decl_arg_types;
2262 
2263 	  /* This is an ordinary member function.  However, since
2264 	     we're here, we can assume its enclosing class is a
2265 	     template class.  For example,
2266 
2267 	       template <typename T> struct S { void f(); };
2268 	       template <> void S<int>::f() {}
2269 
2270 	     Here, S<int>::f is a non-template, but S<int> is a
2271 	     template class.  If FN has the same type as DECL, we
2272 	     might be in business.  */
2273 
2274 	  if (!DECL_TEMPLATE_INFO (fn))
2275 	    /* Its enclosing class is an explicit specialization
2276 	       of a template class.  This is not a candidate.  */
2277 	    continue;
2278 
2279 	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2280 			    TREE_TYPE (TREE_TYPE (fn))))
2281 	    /* The return types differ.  */
2282 	    continue;
2283 
2284 	  /* Adjust the type of DECL in case FN is a static member.  */
2285 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2286 	  if (DECL_STATIC_FUNCTION_P (fn)
2287 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2288 	    decl_arg_types = TREE_CHAIN (decl_arg_types);
2289 
2290 	  if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2291 			 decl_arg_types))
2292             continue;
2293 
2294 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2295 	      && (type_memfn_rqual (TREE_TYPE (decl))
2296 		  != type_memfn_rqual (TREE_TYPE (fn))))
2297 	    continue;
2298 
2299           // If the deduced arguments do not satisfy the constraints,
2300           // this is not a candidate.
2301           if (flag_concepts && !constraints_satisfied_p (fn))
2302             continue;
2303 
2304           // Add the candidate.
2305           candidates = tree_cons (NULL_TREE, fn, candidates);
2306 	}
2307     }
2308 
2309   if (templates && TREE_CHAIN (templates))
2310     {
2311       /* We have:
2312 
2313 	   [temp.expl.spec]
2314 
2315 	   It is possible for a specialization with a given function
2316 	   signature to be instantiated from more than one function
2317 	   template.  In such cases, explicit specification of the
2318 	   template arguments must be used to uniquely identify the
2319 	   function template specialization being specialized.
2320 
2321 	 Note that here, there's no suggestion that we're supposed to
2322 	 determine which of the candidate templates is most
2323 	 specialized.  However, we, also have:
2324 
2325 	   [temp.func.order]
2326 
2327 	   Partial ordering of overloaded function template
2328 	   declarations is used in the following contexts to select
2329 	   the function template to which a function template
2330 	   specialization refers:
2331 
2332 	   -- when an explicit specialization refers to a function
2333 	      template.
2334 
2335 	 So, we do use the partial ordering rules, at least for now.
2336 	 This extension can only serve to make invalid programs valid,
2337 	 so it's safe.  And, there is strong anecdotal evidence that
2338 	 the committee intended the partial ordering rules to apply;
2339 	 the EDG front end has that behavior, and John Spicer claims
2340 	 that the committee simply forgot to delete the wording in
2341 	 [temp.expl.spec].  */
2342       tree tmpl = most_specialized_instantiation (templates);
2343       if (tmpl != error_mark_node)
2344 	{
2345 	  templates = tmpl;
2346 	  TREE_CHAIN (templates) = NULL_TREE;
2347 	}
2348     }
2349 
2350   // Concepts allows multiple declarations of member functions
2351   // with the same signature. Like above, we need to rely on
2352   // on the partial ordering of those candidates to determine which
2353   // is the best.
2354   if (flag_concepts && candidates && TREE_CHAIN (candidates))
2355     {
2356       if (tree cand = most_constrained_function (candidates))
2357         {
2358           candidates = cand;
2359           TREE_CHAIN (cand) = NULL_TREE;
2360         }
2361     }
2362 
2363   if (templates == NULL_TREE && candidates == NULL_TREE)
2364     {
2365       error ("template-id %qD for %q+D does not match any template "
2366 	     "declaration", template_id, decl);
2367       if (header_count && header_count != template_count + 1)
2368 	inform (input_location, "saw %d %<template<>%>, need %d for "
2369 		"specializing a member function template",
2370 		header_count, template_count + 1);
2371       else
2372 	print_candidates (orig_fns);
2373       return error_mark_node;
2374     }
2375   else if ((templates && TREE_CHAIN (templates))
2376 	   || (candidates && TREE_CHAIN (candidates))
2377 	   || (templates && candidates))
2378     {
2379       error ("ambiguous template specialization %qD for %q+D",
2380 	     template_id, decl);
2381       candidates = chainon (candidates, templates);
2382       print_candidates (candidates);
2383       return error_mark_node;
2384     }
2385 
2386   /* We have one, and exactly one, match.  */
2387   if (candidates)
2388     {
2389       tree fn = TREE_VALUE (candidates);
2390       *targs_out = copy_node (DECL_TI_ARGS (fn));
2391 
2392       // Propagate the candidate's constraints to the declaration.
2393       set_constraints (decl, get_constraints (fn));
2394 
2395       /* DECL is a re-declaration or partial instantiation of a template
2396 	 function.  */
2397       if (TREE_CODE (fn) == TEMPLATE_DECL)
2398 	return fn;
2399       /* It was a specialization of an ordinary member function in a
2400 	 template class.  */
2401       return DECL_TI_TEMPLATE (fn);
2402     }
2403 
2404   /* It was a specialization of a template.  */
2405   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2406   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2407     {
2408       *targs_out = copy_node (targs);
2409       SET_TMPL_ARGS_LEVEL (*targs_out,
2410 			   TMPL_ARGS_DEPTH (*targs_out),
2411 			   TREE_PURPOSE (templates));
2412     }
2413   else
2414     *targs_out = TREE_PURPOSE (templates);
2415   return TREE_VALUE (templates);
2416 }
2417 
2418 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2419    but with the default argument values filled in from those in the
2420    TMPL_TYPES.  */
2421 
2422 static tree
2423 copy_default_args_to_explicit_spec_1 (tree spec_types,
2424 				      tree tmpl_types)
2425 {
2426   tree new_spec_types;
2427 
2428   if (!spec_types)
2429     return NULL_TREE;
2430 
2431   if (spec_types == void_list_node)
2432     return void_list_node;
2433 
2434   /* Substitute into the rest of the list.  */
2435   new_spec_types =
2436     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2437 					  TREE_CHAIN (tmpl_types));
2438 
2439   /* Add the default argument for this parameter.  */
2440   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2441 			 TREE_VALUE (spec_types),
2442 			 new_spec_types);
2443 }
2444 
2445 /* DECL is an explicit specialization.  Replicate default arguments
2446    from the template it specializes.  (That way, code like:
2447 
2448      template <class T> void f(T = 3);
2449      template <> void f(double);
2450      void g () { f (); }
2451 
2452    works, as required.)  An alternative approach would be to look up
2453    the correct default arguments at the call-site, but this approach
2454    is consistent with how implicit instantiations are handled.  */
2455 
2456 static void
2457 copy_default_args_to_explicit_spec (tree decl)
2458 {
2459   tree tmpl;
2460   tree spec_types;
2461   tree tmpl_types;
2462   tree new_spec_types;
2463   tree old_type;
2464   tree new_type;
2465   tree t;
2466   tree object_type = NULL_TREE;
2467   tree in_charge = NULL_TREE;
2468   tree vtt = NULL_TREE;
2469 
2470   /* See if there's anything we need to do.  */
2471   tmpl = DECL_TI_TEMPLATE (decl);
2472   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2473   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2474     if (TREE_PURPOSE (t))
2475       break;
2476   if (!t)
2477     return;
2478 
2479   old_type = TREE_TYPE (decl);
2480   spec_types = TYPE_ARG_TYPES (old_type);
2481 
2482   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2483     {
2484       /* Remove the this pointer, but remember the object's type for
2485 	 CV quals.  */
2486       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2487       spec_types = TREE_CHAIN (spec_types);
2488       tmpl_types = TREE_CHAIN (tmpl_types);
2489 
2490       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2491 	{
2492 	  /* DECL may contain more parameters than TMPL due to the extra
2493 	     in-charge parameter in constructors and destructors.  */
2494 	  in_charge = spec_types;
2495 	  spec_types = TREE_CHAIN (spec_types);
2496 	}
2497       if (DECL_HAS_VTT_PARM_P (decl))
2498 	{
2499 	  vtt = spec_types;
2500 	  spec_types = TREE_CHAIN (spec_types);
2501 	}
2502     }
2503 
2504   /* Compute the merged default arguments.  */
2505   new_spec_types =
2506     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2507 
2508   /* Compute the new FUNCTION_TYPE.  */
2509   if (object_type)
2510     {
2511       if (vtt)
2512 	new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2513 					 TREE_VALUE (vtt),
2514 					 new_spec_types);
2515 
2516       if (in_charge)
2517 	/* Put the in-charge parameter back.  */
2518 	new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2519 					 TREE_VALUE (in_charge),
2520 					 new_spec_types);
2521 
2522       new_type = build_method_type_directly (object_type,
2523 					     TREE_TYPE (old_type),
2524 					     new_spec_types);
2525     }
2526   else
2527     new_type = build_function_type (TREE_TYPE (old_type),
2528 				    new_spec_types);
2529   new_type = cp_build_type_attribute_variant (new_type,
2530 					      TYPE_ATTRIBUTES (old_type));
2531   new_type = build_exception_variant (new_type,
2532 				      TYPE_RAISES_EXCEPTIONS (old_type));
2533 
2534   if (TYPE_HAS_LATE_RETURN_TYPE (old_type))
2535     TYPE_HAS_LATE_RETURN_TYPE (new_type) = 1;
2536 
2537   TREE_TYPE (decl) = new_type;
2538 }
2539 
2540 /* Return the number of template headers we expect to see for a definition
2541    or specialization of CTYPE or one of its non-template members.  */
2542 
2543 int
2544 num_template_headers_for_class (tree ctype)
2545 {
2546   int num_templates = 0;
2547 
2548   while (ctype && CLASS_TYPE_P (ctype))
2549     {
2550       /* You're supposed to have one `template <...>' for every
2551 	 template class, but you don't need one for a full
2552 	 specialization.  For example:
2553 
2554 	 template <class T> struct S{};
2555 	 template <> struct S<int> { void f(); };
2556 	 void S<int>::f () {}
2557 
2558 	 is correct; there shouldn't be a `template <>' for the
2559 	 definition of `S<int>::f'.  */
2560       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2561 	/* If CTYPE does not have template information of any
2562 	   kind,  then it is not a template, nor is it nested
2563 	   within a template.  */
2564 	break;
2565       if (explicit_class_specialization_p (ctype))
2566 	break;
2567       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2568 	++num_templates;
2569 
2570       ctype = TYPE_CONTEXT (ctype);
2571     }
2572 
2573   return num_templates;
2574 }
2575 
2576 /* Do a simple sanity check on the template headers that precede the
2577    variable declaration DECL.  */
2578 
2579 void
2580 check_template_variable (tree decl)
2581 {
2582   tree ctx = CP_DECL_CONTEXT (decl);
2583   int wanted = num_template_headers_for_class (ctx);
2584   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2585       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2586     {
2587       if (cxx_dialect < cxx14)
2588         pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2589                  "variable templates only available with "
2590                  "-std=c++14 or -std=gnu++14");
2591 
2592       // Namespace-scope variable templates should have a template header.
2593       ++wanted;
2594     }
2595   if (template_header_count > wanted)
2596     {
2597       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2598 			     "too many template headers for %qD "
2599 	                     "(should be %d)",
2600 			     decl, wanted);
2601       if (warned && CLASS_TYPE_P (ctx)
2602 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2603 	inform (DECL_SOURCE_LOCATION (decl),
2604 		"members of an explicitly specialized class are defined "
2605 		"without a template header");
2606     }
2607 }
2608 
2609 /* An explicit specialization whose declarator-id or class-head-name is not
2610    qualified shall be declared in the nearest enclosing namespace of the
2611    template, or, if the namespace is inline (7.3.1), any namespace from its
2612    enclosing namespace set.
2613 
2614    If the name declared in the explicit instantiation is an unqualified name,
2615    the explicit instantiation shall appear in the namespace where its template
2616    is declared or, if that namespace is inline (7.3.1), any namespace from its
2617    enclosing namespace set.  */
2618 
2619 void
2620 check_unqualified_spec_or_inst (tree t, location_t loc)
2621 {
2622   tree tmpl = most_general_template (t);
2623   if (DECL_NAMESPACE_SCOPE_P (tmpl)
2624       && !is_nested_namespace (current_namespace,
2625 			       CP_DECL_CONTEXT (tmpl), true))
2626     {
2627       if (processing_specialization)
2628 	permerror (loc, "explicit specialization of %qD outside its "
2629 		   "namespace must use a nested-name-specifier", tmpl);
2630       else if (processing_explicit_instantiation
2631 	       && cxx_dialect >= cxx11)
2632 	/* This was allowed in C++98, so only pedwarn.  */
2633 	pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2634 		 "outside its namespace must use a nested-name-"
2635 		 "specifier", tmpl);
2636     }
2637 }
2638 
2639 /* Warn for a template specialization SPEC that is missing some of a set
2640    of function or type attributes that the template TEMPL is declared with.
2641    ATTRLIST is a list of additional attributes that SPEC should be taken
2642    to ultimately be declared with.  */
2643 
2644 static void
2645 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2646 {
2647   if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2648     tmpl = DECL_TEMPLATE_RESULT (tmpl);
2649 
2650   if (TREE_CODE (tmpl) != FUNCTION_DECL)
2651     return;
2652 
2653   /* Avoid warning if either declaration or its type is deprecated.  */
2654   if (TREE_DEPRECATED (tmpl)
2655       || TREE_DEPRECATED (spec))
2656     return;
2657 
2658   tree tmpl_type = TREE_TYPE (tmpl);
2659   tree spec_type = TREE_TYPE (spec);
2660 
2661   if (TREE_DEPRECATED (tmpl_type)
2662       || TREE_DEPRECATED (spec_type)
2663       || TREE_DEPRECATED (TREE_TYPE (tmpl_type))
2664       || TREE_DEPRECATED (TREE_TYPE (spec_type)))
2665     return;
2666 
2667   tree tmpl_attrs[] = { DECL_ATTRIBUTES (tmpl), TYPE_ATTRIBUTES (tmpl_type) };
2668   tree spec_attrs[] = { DECL_ATTRIBUTES (spec), TYPE_ATTRIBUTES (spec_type) };
2669 
2670   if (!spec_attrs[0])
2671     spec_attrs[0] = attrlist;
2672   else if (!spec_attrs[1])
2673     spec_attrs[1] = attrlist;
2674 
2675   /* Avoid warning if the primary has no attributes.  */
2676   if (!tmpl_attrs[0] && !tmpl_attrs[1])
2677     return;
2678 
2679   /* Avoid warning if either declaration contains an attribute on
2680      the white list below.  */
2681   const char* const whitelist[] = {
2682     "error", "warning"
2683   };
2684 
2685   for (unsigned i = 0; i != 2; ++i)
2686     for (unsigned j = 0; j != sizeof whitelist / sizeof *whitelist; ++j)
2687       if (lookup_attribute (whitelist[j], tmpl_attrs[i])
2688 	  || lookup_attribute (whitelist[j], spec_attrs[i]))
2689 	return;
2690 
2691   /* Avoid warning if the difference between the primary and
2692      the specialization is not in one of the attributes below.  */
2693   const char* const blacklist[] = {
2694     "alloc_align", "alloc_size", "assume_aligned", "format",
2695     "format_arg", "malloc", "nonnull"
2696   };
2697 
2698   /* Put together a list of the black listed attributes that the primary
2699      template is declared with that the specialization is not, in case
2700      it's not apparent from the most recent declaration of the primary.  */
2701   unsigned nattrs = 0;
2702   pretty_printer str;
2703 
2704   for (unsigned i = 0; i != sizeof blacklist / sizeof *blacklist; ++i)
2705     {
2706       for (unsigned j = 0; j != 2; ++j)
2707 	{
2708 	  if (!lookup_attribute (blacklist[i], tmpl_attrs[j]))
2709 	    continue;
2710 
2711 	  for (unsigned k = 0; k != 1 + !!spec_attrs[1]; ++k)
2712 	    {
2713 	      if (lookup_attribute (blacklist[i], spec_attrs[k]))
2714 		break;
2715 
2716 	      if (nattrs)
2717 		pp_string (&str, ", ");
2718 	      pp_begin_quote (&str, pp_show_color (global_dc->printer));
2719 	      pp_string (&str, blacklist[i]);
2720 	      pp_end_quote (&str, pp_show_color (global_dc->printer));
2721 	      ++nattrs;
2722 	    }
2723 	}
2724     }
2725 
2726   if (!nattrs)
2727     return;
2728 
2729   if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2730 		  "explicit specialization %q#D may be missing attributes",
2731 		  spec))
2732     inform (DECL_SOURCE_LOCATION (tmpl),
2733 	    nattrs > 1
2734 	    ? G_("missing primary template attributes %s")
2735 	    : G_("missing primary template attribute %s"),
2736 	    pp_formatted_text (&str));
2737 }
2738 
2739 /* Check to see if the function just declared, as indicated in
2740    DECLARATOR, and in DECL, is a specialization of a function
2741    template.  We may also discover that the declaration is an explicit
2742    instantiation at this point.
2743 
2744    Returns DECL, or an equivalent declaration that should be used
2745    instead if all goes well.  Issues an error message if something is
2746    amiss.  Returns error_mark_node if the error is not easily
2747    recoverable.
2748 
2749    FLAGS is a bitmask consisting of the following flags:
2750 
2751    2: The function has a definition.
2752    4: The function is a friend.
2753 
2754    The TEMPLATE_COUNT is the number of references to qualifying
2755    template classes that appeared in the name of the function.  For
2756    example, in
2757 
2758      template <class T> struct S { void f(); };
2759      void S<int>::f();
2760 
2761    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2762    classes are not counted in the TEMPLATE_COUNT, so that in
2763 
2764      template <class T> struct S {};
2765      template <> struct S<int> { void f(); }
2766      template <> void S<int>::f();
2767 
2768    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2769    invalid; there should be no template <>.)
2770 
2771    If the function is a specialization, it is marked as such via
2772    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2773    is set up correctly, and it is added to the list of specializations
2774    for that template.  */
2775 
2776 tree
2777 check_explicit_specialization (tree declarator,
2778 			       tree decl,
2779 			       int template_count,
2780 			       int flags,
2781 			       tree attrlist)
2782 {
2783   int have_def = flags & 2;
2784   int is_friend = flags & 4;
2785   bool is_concept = flags & 8;
2786   int specialization = 0;
2787   int explicit_instantiation = 0;
2788   int member_specialization = 0;
2789   tree ctype = DECL_CLASS_CONTEXT (decl);
2790   tree dname = DECL_NAME (decl);
2791   tmpl_spec_kind tsk;
2792 
2793   if (is_friend)
2794     {
2795       if (!processing_specialization)
2796 	tsk = tsk_none;
2797       else
2798 	tsk = tsk_excessive_parms;
2799     }
2800   else
2801     tsk = current_tmpl_spec_kind (template_count);
2802 
2803   switch (tsk)
2804     {
2805     case tsk_none:
2806       if (processing_specialization && !VAR_P (decl))
2807 	{
2808 	  specialization = 1;
2809 	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2810 	}
2811       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2812 	{
2813 	  if (is_friend)
2814 	    /* This could be something like:
2815 
2816 	       template <class T> void f(T);
2817 	       class S { friend void f<>(int); }  */
2818 	    specialization = 1;
2819 	  else
2820 	    {
2821 	      /* This case handles bogus declarations like template <>
2822 		 template <class T> void f<int>(); */
2823 
2824 	      error ("template-id %qD in declaration of primary template",
2825 		     declarator);
2826 	      return decl;
2827 	    }
2828 	}
2829       break;
2830 
2831     case tsk_invalid_member_spec:
2832       /* The error has already been reported in
2833 	 check_specialization_scope.  */
2834       return error_mark_node;
2835 
2836     case tsk_invalid_expl_inst:
2837       error ("template parameter list used in explicit instantiation");
2838 
2839       /* Fall through.  */
2840 
2841     case tsk_expl_inst:
2842       if (have_def)
2843 	error ("definition provided for explicit instantiation");
2844 
2845       explicit_instantiation = 1;
2846       break;
2847 
2848     case tsk_excessive_parms:
2849     case tsk_insufficient_parms:
2850       if (tsk == tsk_excessive_parms)
2851 	error ("too many template parameter lists in declaration of %qD",
2852 	       decl);
2853       else if (template_header_count)
2854 	error("too few template parameter lists in declaration of %qD", decl);
2855       else
2856 	error("explicit specialization of %qD must be introduced by "
2857 	      "%<template <>%>", decl);
2858 
2859       /* Fall through.  */
2860     case tsk_expl_spec:
2861       if (is_concept)
2862         error ("explicit specialization declared %<concept%>");
2863 
2864       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2865 	/* In cases like template<> constexpr bool v = true;
2866 	   We'll give an error in check_template_variable.  */
2867 	break;
2868 
2869       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2870       if (ctype)
2871 	member_specialization = 1;
2872       else
2873 	specialization = 1;
2874       break;
2875 
2876     case tsk_template:
2877       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2878 	{
2879 	  /* This case handles bogus declarations like template <>
2880 	     template <class T> void f<int>(); */
2881 
2882 	  if (!uses_template_parms (declarator))
2883 	    error ("template-id %qD in declaration of primary template",
2884 		   declarator);
2885 	  else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2886 	    {
2887 	      /* Partial specialization of variable template.  */
2888 	      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2889 	      specialization = 1;
2890 	      goto ok;
2891 	    }
2892 	  else if (cxx_dialect < cxx14)
2893 	    error ("non-type partial specialization %qD "
2894 		   "is not allowed", declarator);
2895 	  else
2896 	    error ("non-class, non-variable partial specialization %qD "
2897 		   "is not allowed", declarator);
2898 	  return decl;
2899 	ok:;
2900 	}
2901 
2902       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2903 	/* This is a specialization of a member template, without
2904 	   specialization the containing class.  Something like:
2905 
2906 	     template <class T> struct S {
2907 	       template <class U> void f (U);
2908 	     };
2909 	     template <> template <class U> void S<int>::f(U) {}
2910 
2911 	   That's a specialization -- but of the entire template.  */
2912 	specialization = 1;
2913       break;
2914 
2915     default:
2916       gcc_unreachable ();
2917     }
2918 
2919   if ((specialization || member_specialization)
2920       /* This doesn't apply to variable templates.  */
2921       && (TREE_CODE (TREE_TYPE (decl)) == FUNCTION_TYPE
2922           || TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE))
2923     {
2924       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2925       for (; t; t = TREE_CHAIN (t))
2926 	if (TREE_PURPOSE (t))
2927 	  {
2928 	    permerror (input_location,
2929 		       "default argument specified in explicit specialization");
2930 	    break;
2931 	  }
2932     }
2933 
2934   if (specialization || member_specialization || explicit_instantiation)
2935     {
2936       tree tmpl = NULL_TREE;
2937       tree targs = NULL_TREE;
2938       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2939 
2940       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2941       if (!was_template_id)
2942 	{
2943 	  tree fns;
2944 
2945 	  gcc_assert (identifier_p (declarator));
2946 	  if (ctype)
2947 	    fns = dname;
2948 	  else
2949 	    {
2950 	      /* If there is no class context, the explicit instantiation
2951 		 must be at namespace scope.  */
2952 	      gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2953 
2954 	      /* Find the namespace binding, using the declaration
2955 		 context.  */
2956 	      fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2957 					   false, true);
2958 	      if (fns == error_mark_node)
2959 		/* If lookup fails, look for a friend declaration so we can
2960 		   give a better diagnostic.  */
2961 		fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2962 					     /*type*/false, /*complain*/true,
2963 					     /*hidden*/true);
2964 
2965 	      if (fns == error_mark_node || !is_overloaded_fn (fns))
2966 		{
2967 		  error ("%qD is not a template function", dname);
2968 		  fns = error_mark_node;
2969 		}
2970 	    }
2971 
2972 	  declarator = lookup_template_function (fns, NULL_TREE);
2973 	}
2974 
2975       if (declarator == error_mark_node)
2976 	return error_mark_node;
2977 
2978       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2979 	{
2980 	  if (!explicit_instantiation)
2981 	    /* A specialization in class scope.  This is invalid,
2982 	       but the error will already have been flagged by
2983 	       check_specialization_scope.  */
2984 	    return error_mark_node;
2985 	  else
2986 	    {
2987 	      /* It's not valid to write an explicit instantiation in
2988 		 class scope, e.g.:
2989 
2990 		   class C { template void f(); }
2991 
2992 		   This case is caught by the parser.  However, on
2993 		   something like:
2994 
2995 		   template class C { void f(); };
2996 
2997 		   (which is invalid) we can get here.  The error will be
2998 		   issued later.  */
2999 	      ;
3000 	    }
3001 
3002 	  return decl;
3003 	}
3004       else if (ctype != NULL_TREE
3005 	       && (identifier_p (TREE_OPERAND (declarator, 0))))
3006 	{
3007 	  // We'll match variable templates in start_decl.
3008 	  if (VAR_P (decl))
3009 	    return decl;
3010 
3011 	  /* Find the list of functions in ctype that have the same
3012 	     name as the declared function.  */
3013 	  tree name = TREE_OPERAND (declarator, 0);
3014 
3015 	  if (constructor_name_p (name, ctype))
3016 	    {
3017 	      if (DECL_CONSTRUCTOR_P (decl)
3018 		  ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3019 		  : !CLASSTYPE_DESTRUCTOR (ctype))
3020 		{
3021 		  /* From [temp.expl.spec]:
3022 
3023 		     If such an explicit specialization for the member
3024 		     of a class template names an implicitly-declared
3025 		     special member function (clause _special_), the
3026 		     program is ill-formed.
3027 
3028 		     Similar language is found in [temp.explicit].  */
3029 		  error ("specialization of implicitly-declared special member function");
3030 		  return error_mark_node;
3031 		}
3032 
3033 	      name = DECL_NAME (decl);
3034 	    }
3035 
3036 	  /* For a type-conversion operator, We might be looking for
3037 	     `operator int' which will be a specialization of
3038 	     `operator T'.  Grab all the conversion operators, and
3039 	     then select from them.  */
3040 	  tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3041 				      ? conv_op_identifier : name);
3042 
3043 	  if (fns == NULL_TREE)
3044 	    {
3045 	      error ("no member function %qD declared in %qT", name, ctype);
3046 	      return error_mark_node;
3047 	    }
3048 	  else
3049 	    TREE_OPERAND (declarator, 0) = fns;
3050 	}
3051 
3052       /* Figure out what exactly is being specialized at this point.
3053 	 Note that for an explicit instantiation, even one for a
3054 	 member function, we cannot tell a priori whether the
3055 	 instantiation is for a member template, or just a member
3056 	 function of a template class.  Even if a member template is
3057 	 being instantiated, the member template arguments may be
3058 	 elided if they can be deduced from the rest of the
3059 	 declaration.  */
3060       tmpl = determine_specialization (declarator, decl,
3061 				       &targs,
3062 				       member_specialization,
3063 				       template_count,
3064 				       tsk);
3065 
3066       if (!tmpl || tmpl == error_mark_node)
3067 	/* We couldn't figure out what this declaration was
3068 	   specializing.  */
3069 	return error_mark_node;
3070       else
3071 	{
3072 	  if (TREE_CODE (decl) == FUNCTION_DECL
3073 	      && DECL_HIDDEN_FRIEND_P (tmpl))
3074 	    {
3075 	      if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3076 			   "friend declaration %qD is not visible to "
3077 			   "explicit specialization", tmpl))
3078 		inform (DECL_SOURCE_LOCATION (tmpl),
3079 			"friend declaration here");
3080 	    }
3081 	  else if (!ctype && !is_friend
3082 		   && CP_DECL_CONTEXT (decl) == current_namespace)
3083 	    check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3084 
3085 	  tree gen_tmpl = most_general_template (tmpl);
3086 
3087 	  if (explicit_instantiation)
3088 	    {
3089 	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3090 		 is done by do_decl_instantiation later.  */
3091 
3092 	      int arg_depth = TMPL_ARGS_DEPTH (targs);
3093 	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3094 
3095 	      if (arg_depth > parm_depth)
3096 		{
3097 		  /* If TMPL is not the most general template (for
3098 		     example, if TMPL is a friend template that is
3099 		     injected into namespace scope), then there will
3100 		     be too many levels of TARGS.  Remove some of them
3101 		     here.  */
3102 		  int i;
3103 		  tree new_targs;
3104 
3105 		  new_targs = make_tree_vec (parm_depth);
3106 		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3107 		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3108 		      = TREE_VEC_ELT (targs, i);
3109 		  targs = new_targs;
3110 		}
3111 
3112 	      return instantiate_template (tmpl, targs, tf_error);
3113 	    }
3114 
3115 	  /* If we thought that the DECL was a member function, but it
3116 	     turns out to be specializing a static member function,
3117 	     make DECL a static member function as well.  */
3118 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3119 	      && DECL_STATIC_FUNCTION_P (tmpl)
3120 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3121 	    revert_static_member_fn (decl);
3122 
3123 	  /* If this is a specialization of a member template of a
3124 	     template class, we want to return the TEMPLATE_DECL, not
3125 	     the specialization of it.  */
3126 	  if (tsk == tsk_template && !was_template_id)
3127 	    {
3128 	      tree result = DECL_TEMPLATE_RESULT (tmpl);
3129 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3130 	      DECL_INITIAL (result) = NULL_TREE;
3131 	      if (have_def)
3132 		{
3133 		  tree parm;
3134 		  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3135 		  DECL_SOURCE_LOCATION (result)
3136 		    = DECL_SOURCE_LOCATION (decl);
3137 		  /* We want to use the argument list specified in the
3138 		     definition, not in the original declaration.  */
3139 		  DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3140 		  for (parm = DECL_ARGUMENTS (result); parm;
3141 		       parm = DECL_CHAIN (parm))
3142 		    DECL_CONTEXT (parm) = result;
3143 		}
3144 	      return register_specialization (tmpl, gen_tmpl, targs,
3145 					      is_friend, 0);
3146 	    }
3147 
3148 	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
3149 	  DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3150 
3151 	  if (was_template_id)
3152 	    TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3153 
3154 	  /* Inherit default function arguments from the template
3155 	     DECL is specializing.  */
3156 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3157 	    copy_default_args_to_explicit_spec (decl);
3158 
3159 	  /* This specialization has the same protection as the
3160 	     template it specializes.  */
3161 	  TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3162 	  TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3163 
3164           /* 7.1.1-1 [dcl.stc]
3165 
3166              A storage-class-specifier shall not be specified in an
3167              explicit specialization...
3168 
3169              The parser rejects these, so unless action is taken here,
3170              explicit function specializations will always appear with
3171              global linkage.
3172 
3173              The action recommended by the C++ CWG in response to C++
3174              defect report 605 is to make the storage class and linkage
3175              of the explicit specialization match the templated function:
3176 
3177              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3178            */
3179           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3180             {
3181               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3182               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3183 
3184               /* A concept cannot be specialized.  */
3185               if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3186                 {
3187                   error ("explicit specialization of function concept %qD",
3188                          gen_tmpl);
3189                   return error_mark_node;
3190                 }
3191 
3192               /* This specialization has the same linkage and visibility as
3193                  the function template it specializes.  */
3194               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3195 	      if (! TREE_PUBLIC (decl))
3196 		{
3197 		  DECL_INTERFACE_KNOWN (decl) = 1;
3198 		  DECL_NOT_REALLY_EXTERN (decl) = 1;
3199 		}
3200               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3201               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3202                 {
3203                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
3204                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3205                 }
3206             }
3207 
3208 	  /* If DECL is a friend declaration, declared using an
3209 	     unqualified name, the namespace associated with DECL may
3210 	     have been set incorrectly.  For example, in:
3211 
3212 	       template <typename T> void f(T);
3213 	       namespace N {
3214 		 struct S { friend void f<int>(int); }
3215 	       }
3216 
3217 	     we will have set the DECL_CONTEXT for the friend
3218 	     declaration to N, rather than to the global namespace.  */
3219 	  if (DECL_NAMESPACE_SCOPE_P (decl))
3220 	    DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3221 
3222 	  if (is_friend && !have_def)
3223 	    /* This is not really a declaration of a specialization.
3224 	       It's just the name of an instantiation.  But, it's not
3225 	       a request for an instantiation, either.  */
3226 	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
3227 	  else if (TREE_CODE (decl) == FUNCTION_DECL)
3228 	    /* A specialization is not necessarily COMDAT.  */
3229 	    DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3230 				  && DECL_DECLARED_INLINE_P (decl));
3231 	  else if (VAR_P (decl))
3232 	    DECL_COMDAT (decl) = false;
3233 
3234 	  /* If this is a full specialization, register it so that we can find
3235 	     it again.  Partial specializations will be registered in
3236 	     process_partial_specialization.  */
3237 	  if (!processing_template_decl)
3238 	    {
3239 	      warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3240 
3241 	      decl = register_specialization (decl, gen_tmpl, targs,
3242 					      is_friend, 0);
3243 	    }
3244 
3245 
3246 	  /* A 'structor should already have clones.  */
3247 	  gcc_assert (decl == error_mark_node
3248 		      || variable_template_p (tmpl)
3249 		      || !(DECL_CONSTRUCTOR_P (decl)
3250 			   || DECL_DESTRUCTOR_P (decl))
3251 		      || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3252 	}
3253     }
3254 
3255   return decl;
3256 }
3257 
3258 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3259    parameters.  These are represented in the same format used for
3260    DECL_TEMPLATE_PARMS.  */
3261 
3262 int
3263 comp_template_parms (const_tree parms1, const_tree parms2)
3264 {
3265   const_tree p1;
3266   const_tree p2;
3267 
3268   if (parms1 == parms2)
3269     return 1;
3270 
3271   for (p1 = parms1, p2 = parms2;
3272        p1 != NULL_TREE && p2 != NULL_TREE;
3273        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3274     {
3275       tree t1 = TREE_VALUE (p1);
3276       tree t2 = TREE_VALUE (p2);
3277       int i;
3278 
3279       gcc_assert (TREE_CODE (t1) == TREE_VEC);
3280       gcc_assert (TREE_CODE (t2) == TREE_VEC);
3281 
3282       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3283 	return 0;
3284 
3285       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3286 	{
3287           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3288           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3289 
3290           /* If either of the template parameters are invalid, assume
3291              they match for the sake of error recovery. */
3292           if (error_operand_p (parm1) || error_operand_p (parm2))
3293             return 1;
3294 
3295 	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
3296 	    return 0;
3297 
3298 	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3299               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3300                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3301 	    continue;
3302 	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3303 	    return 0;
3304 	}
3305     }
3306 
3307   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3308     /* One set of parameters has more parameters lists than the
3309        other.  */
3310     return 0;
3311 
3312   return 1;
3313 }
3314 
3315 /* Determine whether PARM is a parameter pack.  */
3316 
3317 bool
3318 template_parameter_pack_p (const_tree parm)
3319 {
3320   /* Determine if we have a non-type template parameter pack.  */
3321   if (TREE_CODE (parm) == PARM_DECL)
3322     return (DECL_TEMPLATE_PARM_P (parm)
3323             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3324   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3325     return TEMPLATE_PARM_PARAMETER_PACK (parm);
3326 
3327   /* If this is a list of template parameters, we could get a
3328      TYPE_DECL or a TEMPLATE_DECL.  */
3329   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3330     parm = TREE_TYPE (parm);
3331 
3332   /* Otherwise it must be a type template parameter.  */
3333   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3334 	   || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3335 	  && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3336 }
3337 
3338 /* Determine if T is a function parameter pack.  */
3339 
3340 bool
3341 function_parameter_pack_p (const_tree t)
3342 {
3343   if (t && TREE_CODE (t) == PARM_DECL)
3344     return DECL_PACK_P (t);
3345   return false;
3346 }
3347 
3348 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3349    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
3350 
3351 tree
3352 get_function_template_decl (const_tree primary_func_tmpl_inst)
3353 {
3354   if (! primary_func_tmpl_inst
3355       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3356       || ! primary_template_specialization_p (primary_func_tmpl_inst))
3357     return NULL;
3358 
3359   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3360 }
3361 
3362 /* Return true iff the function parameter PARAM_DECL was expanded
3363    from the function parameter pack PACK.  */
3364 
3365 bool
3366 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3367 {
3368   if (DECL_ARTIFICIAL (param_decl)
3369       || !function_parameter_pack_p (pack))
3370     return false;
3371 
3372   /* The parameter pack and its pack arguments have the same
3373      DECL_PARM_INDEX.  */
3374   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3375 }
3376 
3377 /* Determine whether ARGS describes a variadic template args list,
3378    i.e., one that is terminated by a template argument pack.  */
3379 
3380 static bool
3381 template_args_variadic_p (tree args)
3382 {
3383   int nargs;
3384   tree last_parm;
3385 
3386   if (args == NULL_TREE)
3387     return false;
3388 
3389   args = INNERMOST_TEMPLATE_ARGS (args);
3390   nargs = TREE_VEC_LENGTH (args);
3391 
3392   if (nargs == 0)
3393     return false;
3394 
3395   last_parm = TREE_VEC_ELT (args, nargs - 1);
3396 
3397   return ARGUMENT_PACK_P (last_parm);
3398 }
3399 
3400 /* Generate a new name for the parameter pack name NAME (an
3401    IDENTIFIER_NODE) that incorporates its */
3402 
3403 static tree
3404 make_ith_pack_parameter_name (tree name, int i)
3405 {
3406   /* Munge the name to include the parameter index.  */
3407 #define NUMBUF_LEN 128
3408   char numbuf[NUMBUF_LEN];
3409   char* newname;
3410   int newname_len;
3411 
3412   if (name == NULL_TREE)
3413     return name;
3414   snprintf (numbuf, NUMBUF_LEN, "%i", i);
3415   newname_len = IDENTIFIER_LENGTH (name)
3416 	        + strlen (numbuf) + 2;
3417   newname = (char*)alloca (newname_len);
3418   snprintf (newname, newname_len,
3419 	    "%s#%i", IDENTIFIER_POINTER (name), i);
3420   return get_identifier (newname);
3421 }
3422 
3423 /* Return true if T is a primary function, class or alias template
3424    specialization, not including the template pattern.  */
3425 
3426 bool
3427 primary_template_specialization_p (const_tree t)
3428 {
3429   if (!t)
3430     return false;
3431 
3432   if (TREE_CODE (t) == FUNCTION_DECL || VAR_P (t))
3433     return (DECL_LANG_SPECIFIC (t)
3434 	    && DECL_USE_TEMPLATE (t)
3435 	    && DECL_TEMPLATE_INFO (t)
3436 	    && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3437   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3438     return (CLASSTYPE_TEMPLATE_INFO (t)
3439 	    && CLASSTYPE_USE_TEMPLATE (t)
3440 	    && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3441   else if (alias_template_specialization_p (t))
3442     return true;
3443   return false;
3444 }
3445 
3446 /* Return true if PARM is a template template parameter.  */
3447 
3448 bool
3449 template_template_parameter_p (const_tree parm)
3450 {
3451   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3452 }
3453 
3454 /* Return true iff PARM is a DECL representing a type template
3455    parameter.  */
3456 
3457 bool
3458 template_type_parameter_p (const_tree parm)
3459 {
3460   return (parm
3461 	  && (TREE_CODE (parm) == TYPE_DECL
3462 	      || TREE_CODE (parm) == TEMPLATE_DECL)
3463 	  && DECL_TEMPLATE_PARM_P (parm));
3464 }
3465 
3466 /* Return the template parameters of T if T is a
3467    primary template instantiation, NULL otherwise.  */
3468 
3469 tree
3470 get_primary_template_innermost_parameters (const_tree t)
3471 {
3472   tree parms = NULL, template_info = NULL;
3473 
3474   if ((template_info = get_template_info (t))
3475       && primary_template_specialization_p (t))
3476     parms = INNERMOST_TEMPLATE_PARMS
3477 	(DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3478 
3479   return parms;
3480 }
3481 
3482 /* Return the template parameters of the LEVELth level from the full list
3483    of template parameters PARMS.  */
3484 
3485 tree
3486 get_template_parms_at_level (tree parms, int level)
3487 {
3488   tree p;
3489   if (!parms
3490       || TREE_CODE (parms) != TREE_LIST
3491       || level > TMPL_PARMS_DEPTH (parms))
3492     return NULL_TREE;
3493 
3494   for (p = parms; p; p = TREE_CHAIN (p))
3495     if (TMPL_PARMS_DEPTH (p) == level)
3496       return p;
3497 
3498   return NULL_TREE;
3499 }
3500 
3501 /* Returns the template arguments of T if T is a template instantiation,
3502    NULL otherwise.  */
3503 
3504 tree
3505 get_template_innermost_arguments (const_tree t)
3506 {
3507   tree args = NULL, template_info = NULL;
3508 
3509   if ((template_info = get_template_info (t))
3510       && TI_ARGS (template_info))
3511     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3512 
3513   return args;
3514 }
3515 
3516 /* Return the argument pack elements of T if T is a template argument pack,
3517    NULL otherwise.  */
3518 
3519 tree
3520 get_template_argument_pack_elems (const_tree t)
3521 {
3522   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3523       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3524     return NULL;
3525 
3526   return ARGUMENT_PACK_ARGS (t);
3527 }
3528 
3529 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3530    ARGUMENT_PACK_SELECT represents. */
3531 
3532 static tree
3533 argument_pack_select_arg (tree t)
3534 {
3535   tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3536   tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3537 
3538   /* If the selected argument is an expansion E, that most likely means we were
3539      called from gen_elem_of_pack_expansion_instantiation during the
3540      substituting of an argument pack (of which the Ith element is a pack
3541      expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3542      In this case, the Ith element resulting from this substituting is going to
3543      be a pack expansion, which pattern is the pattern of E.  Let's return the
3544      pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3545      resulting pack expansion from it.  */
3546   if (PACK_EXPANSION_P (arg))
3547     {
3548       /* Make sure we aren't throwing away arg info.  */
3549       gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3550       arg = PACK_EXPANSION_PATTERN (arg);
3551     }
3552 
3553   return arg;
3554 }
3555 
3556 
3557 /* True iff FN is a function representing a built-in variadic parameter
3558    pack.  */
3559 
3560 bool
3561 builtin_pack_fn_p (tree fn)
3562 {
3563   if (!fn
3564       || TREE_CODE (fn) != FUNCTION_DECL
3565       || !DECL_IS_BUILTIN (fn))
3566     return false;
3567 
3568   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3569     return true;
3570 
3571   return false;
3572 }
3573 
3574 /* True iff CALL is a call to a function representing a built-in variadic
3575    parameter pack.  */
3576 
3577 static bool
3578 builtin_pack_call_p (tree call)
3579 {
3580   if (TREE_CODE (call) != CALL_EXPR)
3581     return false;
3582   return builtin_pack_fn_p (CALL_EXPR_FN (call));
3583 }
3584 
3585 /* Return a TREE_VEC for the expansion of __integer_pack(HI).  */
3586 
3587 static tree
3588 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3589 		     tree in_decl)
3590 {
3591   tree ohi = CALL_EXPR_ARG (call, 0);
3592   tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3593 				   false/*fn*/, true/*int_cst*/);
3594 
3595   if (value_dependent_expression_p (hi))
3596     {
3597       if (hi != ohi)
3598 	{
3599 	  call = copy_node (call);
3600 	  CALL_EXPR_ARG (call, 0) = hi;
3601 	}
3602       tree ex = make_pack_expansion (call, complain);
3603       tree vec = make_tree_vec (1);
3604       TREE_VEC_ELT (vec, 0) = ex;
3605       return vec;
3606     }
3607   else
3608     {
3609       hi = cxx_constant_value (hi);
3610       int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3611 
3612       /* Calculate the largest value of len that won't make the size of the vec
3613 	 overflow an int.  The compiler will exceed resource limits long before
3614 	 this, but it seems a decent place to diagnose.  */
3615       int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3616 
3617       if (len < 0 || len > max)
3618 	{
3619 	  if ((complain & tf_error)
3620 	      && hi != error_mark_node)
3621 	    error ("argument to __integer_pack must be between 0 and %d", max);
3622 	  return error_mark_node;
3623 	}
3624 
3625       tree vec = make_tree_vec (len);
3626 
3627       for (int i = 0; i < len; ++i)
3628 	TREE_VEC_ELT (vec, i) = size_int (i);
3629 
3630       return vec;
3631     }
3632 }
3633 
3634 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3635    CALL.  */
3636 
3637 static tree
3638 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3639 			  tree in_decl)
3640 {
3641   if (!builtin_pack_call_p (call))
3642     return NULL_TREE;
3643 
3644   tree fn = CALL_EXPR_FN (call);
3645 
3646   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3647     return expand_integer_pack (call, args, complain, in_decl);
3648 
3649   return NULL_TREE;
3650 }
3651 
3652 /* Structure used to track the progress of find_parameter_packs_r.  */
3653 struct find_parameter_pack_data
3654 {
3655   /* TREE_LIST that will contain all of the parameter packs found by
3656      the traversal.  */
3657   tree* parameter_packs;
3658 
3659   /* Set of AST nodes that have been visited by the traversal.  */
3660   hash_set<tree> *visited;
3661 
3662   /* True iff we're making a type pack expansion.  */
3663   bool type_pack_expansion_p;
3664 };
3665 
3666 /* Identifies all of the argument packs that occur in a template
3667    argument and appends them to the TREE_LIST inside DATA, which is a
3668    find_parameter_pack_data structure. This is a subroutine of
3669    make_pack_expansion and uses_parameter_packs.  */
3670 static tree
3671 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3672 {
3673   tree t = *tp;
3674   struct find_parameter_pack_data* ppd =
3675     (struct find_parameter_pack_data*)data;
3676   bool parameter_pack_p = false;
3677 
3678   /* Handle type aliases/typedefs.  */
3679   if (TYPE_ALIAS_P (t))
3680     {
3681       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3682 	cp_walk_tree (&TI_ARGS (tinfo),
3683 		      &find_parameter_packs_r,
3684 		      ppd, ppd->visited);
3685       *walk_subtrees = 0;
3686       return NULL_TREE;
3687     }
3688 
3689   /* Identify whether this is a parameter pack or not.  */
3690   switch (TREE_CODE (t))
3691     {
3692     case TEMPLATE_PARM_INDEX:
3693       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3694         parameter_pack_p = true;
3695       break;
3696 
3697     case TEMPLATE_TYPE_PARM:
3698       t = TYPE_MAIN_VARIANT (t);
3699       /* FALLTHRU */
3700     case TEMPLATE_TEMPLATE_PARM:
3701       /* If the placeholder appears in the decl-specifier-seq of a function
3702 	 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3703 	 is a pack expansion, the invented template parameter is a template
3704 	 parameter pack.  */
3705       if (ppd->type_pack_expansion_p && is_auto (t))
3706 	TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3707       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3708         parameter_pack_p = true;
3709       break;
3710 
3711     case FIELD_DECL:
3712     case PARM_DECL:
3713       if (DECL_PACK_P (t))
3714         {
3715           /* We don't want to walk into the type of a PARM_DECL,
3716              because we don't want to see the type parameter pack.  */
3717           *walk_subtrees = 0;
3718 	  parameter_pack_p = true;
3719         }
3720       break;
3721 
3722     case VAR_DECL:
3723       if (DECL_PACK_P (t))
3724         {
3725           /* We don't want to walk into the type of a variadic capture proxy,
3726              because we don't want to see the type parameter pack.  */
3727           *walk_subtrees = 0;
3728 	  parameter_pack_p = true;
3729         }
3730       else if (variable_template_specialization_p (t))
3731 	{
3732 	  cp_walk_tree (&DECL_TI_ARGS (t),
3733 			find_parameter_packs_r,
3734 			ppd, ppd->visited);
3735 	  *walk_subtrees = 0;
3736 	}
3737       break;
3738 
3739     case CALL_EXPR:
3740       if (builtin_pack_call_p (t))
3741 	parameter_pack_p = true;
3742       break;
3743 
3744     case BASES:
3745       parameter_pack_p = true;
3746       break;
3747     default:
3748       /* Not a parameter pack.  */
3749       break;
3750     }
3751 
3752   if (parameter_pack_p)
3753     {
3754       /* Add this parameter pack to the list.  */
3755       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3756     }
3757 
3758   if (TYPE_P (t))
3759     cp_walk_tree (&TYPE_CONTEXT (t),
3760 		  &find_parameter_packs_r, ppd, ppd->visited);
3761 
3762   /* This switch statement will return immediately if we don't find a
3763      parameter pack.  */
3764   switch (TREE_CODE (t))
3765     {
3766     case TEMPLATE_PARM_INDEX:
3767       return NULL_TREE;
3768 
3769     case BOUND_TEMPLATE_TEMPLATE_PARM:
3770       /* Check the template itself.  */
3771       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3772 		    &find_parameter_packs_r, ppd, ppd->visited);
3773       /* Check the template arguments.  */
3774       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd,
3775 		    ppd->visited);
3776       *walk_subtrees = 0;
3777       return NULL_TREE;
3778 
3779     case TEMPLATE_TYPE_PARM:
3780     case TEMPLATE_TEMPLATE_PARM:
3781       return NULL_TREE;
3782 
3783     case PARM_DECL:
3784       return NULL_TREE;
3785 
3786     case DECL_EXPR:
3787       /* Ignore the declaration of a capture proxy for a parameter pack.  */
3788       if (is_capture_proxy (DECL_EXPR_DECL (t)))
3789 	*walk_subtrees = 0;
3790       return NULL_TREE;
3791 
3792     case RECORD_TYPE:
3793       if (TYPE_PTRMEMFUNC_P (t))
3794 	return NULL_TREE;
3795       /* Fall through.  */
3796 
3797     case UNION_TYPE:
3798     case ENUMERAL_TYPE:
3799       if (TYPE_TEMPLATE_INFO (t))
3800 	cp_walk_tree (&TYPE_TI_ARGS (t),
3801 		      &find_parameter_packs_r, ppd, ppd->visited);
3802 
3803       *walk_subtrees = 0;
3804       return NULL_TREE;
3805 
3806     case TEMPLATE_DECL:
3807       if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
3808 	return NULL_TREE;
3809       gcc_fallthrough();
3810 
3811     case CONSTRUCTOR:
3812       cp_walk_tree (&TREE_TYPE (t),
3813 		    &find_parameter_packs_r, ppd, ppd->visited);
3814       return NULL_TREE;
3815 
3816     case TYPENAME_TYPE:
3817       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3818                    ppd, ppd->visited);
3819       *walk_subtrees = 0;
3820       return NULL_TREE;
3821 
3822     case TYPE_PACK_EXPANSION:
3823     case EXPR_PACK_EXPANSION:
3824       *walk_subtrees = 0;
3825       return NULL_TREE;
3826 
3827     case INTEGER_TYPE:
3828       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3829 		    ppd, ppd->visited);
3830       *walk_subtrees = 0;
3831       return NULL_TREE;
3832 
3833     case IDENTIFIER_NODE:
3834       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3835 		    ppd->visited);
3836       *walk_subtrees = 0;
3837       return NULL_TREE;
3838 
3839     case LAMBDA_EXPR:
3840       {
3841 	/* Look at explicit captures.  */
3842 	for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t);
3843 	     cap; cap = TREE_CHAIN (cap))
3844 	  cp_walk_tree (&TREE_VALUE (cap), &find_parameter_packs_r, ppd,
3845 			ppd->visited);
3846 	/* Since we defer implicit capture, look in the body as well.  */
3847 	tree fn = lambda_function (t);
3848 	cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
3849 		      ppd->visited);
3850 	*walk_subtrees = 0;
3851 	return NULL_TREE;
3852       }
3853 
3854     case DECLTYPE_TYPE:
3855       {
3856 	/* When traversing a DECLTYPE_TYPE_EXPR, we need to set
3857 	   type_pack_expansion_p to false so that any placeholders
3858 	   within the expression don't get marked as parameter packs.  */
3859 	bool type_pack_expansion_p = ppd->type_pack_expansion_p;
3860 	ppd->type_pack_expansion_p = false;
3861 	cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
3862 		      ppd, ppd->visited);
3863 	ppd->type_pack_expansion_p = type_pack_expansion_p;
3864 	*walk_subtrees = 0;
3865 	return NULL_TREE;
3866       }
3867 
3868     default:
3869       return NULL_TREE;
3870     }
3871 
3872   return NULL_TREE;
3873 }
3874 
3875 /* Determines if the expression or type T uses any parameter packs.  */
3876 bool
3877 uses_parameter_packs (tree t)
3878 {
3879   tree parameter_packs = NULL_TREE;
3880   struct find_parameter_pack_data ppd;
3881   ppd.parameter_packs = &parameter_packs;
3882   ppd.visited = new hash_set<tree>;
3883   ppd.type_pack_expansion_p = false;
3884   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3885   delete ppd.visited;
3886   return parameter_packs != NULL_TREE;
3887 }
3888 
3889 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3890    representation a base-class initializer into a parameter pack
3891    expansion. If all goes well, the resulting node will be an
3892    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3893    respectively.  */
3894 tree
3895 make_pack_expansion (tree arg, tsubst_flags_t complain)
3896 {
3897   tree result;
3898   tree parameter_packs = NULL_TREE;
3899   bool for_types = false;
3900   struct find_parameter_pack_data ppd;
3901 
3902   if (!arg || arg == error_mark_node)
3903     return arg;
3904 
3905   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
3906     {
3907       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
3908          class initializer.  In this case, the TREE_PURPOSE will be a
3909          _TYPE node (representing the base class expansion we're
3910          initializing) and the TREE_VALUE will be a TREE_LIST
3911          containing the initialization arguments.
3912 
3913          The resulting expansion looks somewhat different from most
3914          expansions. Rather than returning just one _EXPANSION, we
3915          return a TREE_LIST whose TREE_PURPOSE is a
3916          TYPE_PACK_EXPANSION containing the bases that will be
3917          initialized.  The TREE_VALUE will be identical to the
3918          original TREE_VALUE, which is a list of arguments that will
3919          be passed to each base.  We do not introduce any new pack
3920          expansion nodes into the TREE_VALUE (although it is possible
3921          that some already exist), because the TREE_PURPOSE and
3922          TREE_VALUE all need to be expanded together with the same
3923          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3924          resulting TREE_PURPOSE will mention the parameter packs in
3925          both the bases and the arguments to the bases.  */
3926       tree purpose;
3927       tree value;
3928       tree parameter_packs = NULL_TREE;
3929 
3930       /* Determine which parameter packs will be used by the base
3931          class expansion.  */
3932       ppd.visited = new hash_set<tree>;
3933       ppd.parameter_packs = &parameter_packs;
3934       ppd.type_pack_expansion_p = true;
3935       gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
3936       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
3937                     &ppd, ppd.visited);
3938 
3939       if (parameter_packs == NULL_TREE)
3940         {
3941 	  if (complain & tf_error)
3942 	    error ("base initializer expansion %qT contains no parameter packs",
3943 		   arg);
3944           delete ppd.visited;
3945           return error_mark_node;
3946         }
3947 
3948       if (TREE_VALUE (arg) != void_type_node)
3949         {
3950           /* Collect the sets of parameter packs used in each of the
3951              initialization arguments.  */
3952           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3953             {
3954               /* Determine which parameter packs will be expanded in this
3955                  argument.  */
3956               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
3957                             &ppd, ppd.visited);
3958             }
3959         }
3960 
3961       delete ppd.visited;
3962 
3963       /* Create the pack expansion type for the base type.  */
3964       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3965       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3966       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3967       PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
3968 
3969       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3970 	 they will rarely be compared to anything.  */
3971       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3972 
3973       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3974     }
3975 
3976   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3977     for_types = true;
3978 
3979   /* Build the PACK_EXPANSION_* node.  */
3980   result = for_types
3981      ? cxx_make_type (TYPE_PACK_EXPANSION)
3982      : make_node (EXPR_PACK_EXPANSION);
3983   SET_PACK_EXPANSION_PATTERN (result, arg);
3984   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3985     {
3986       /* Propagate type and const-expression information.  */
3987       TREE_TYPE (result) = TREE_TYPE (arg);
3988       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3989       /* Mark this read now, since the expansion might be length 0.  */
3990       mark_exp_read (arg);
3991     }
3992   else
3993     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3994        they will rarely be compared to anything.  */
3995     SET_TYPE_STRUCTURAL_EQUALITY (result);
3996 
3997   /* Determine which parameter packs will be expanded.  */
3998   ppd.parameter_packs = &parameter_packs;
3999   ppd.visited = new hash_set<tree>;
4000   ppd.type_pack_expansion_p = TYPE_P (arg);
4001   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4002   delete ppd.visited;
4003 
4004   /* Make sure we found some parameter packs.  */
4005   if (parameter_packs == NULL_TREE)
4006     {
4007       if (complain & tf_error)
4008 	{
4009 	  if (TYPE_P (arg))
4010 	    error ("expansion pattern %qT contains no argument packs", arg);
4011 	  else
4012 	    error ("expansion pattern %qE contains no argument packs", arg);
4013 	}
4014       return error_mark_node;
4015     }
4016   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4017 
4018   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4019 
4020   return result;
4021 }
4022 
4023 /* Checks T for any "bare" parameter packs, which have not yet been
4024    expanded, and issues an error if any are found. This operation can
4025    only be done on full expressions or types (e.g., an expression
4026    statement, "if" condition, etc.), because we could have expressions like:
4027 
4028      foo(f(g(h(args)))...)
4029 
4030    where "args" is a parameter pack. check_for_bare_parameter_packs
4031    should not be called for the subexpressions args, h(args),
4032    g(h(args)), or f(g(h(args))), because we would produce erroneous
4033    error messages.
4034 
4035    Returns TRUE and emits an error if there were bare parameter packs,
4036    returns FALSE otherwise.  */
4037 bool
4038 check_for_bare_parameter_packs (tree t)
4039 {
4040   tree parameter_packs = NULL_TREE;
4041   struct find_parameter_pack_data ppd;
4042 
4043   if (!processing_template_decl || !t || t == error_mark_node)
4044     return false;
4045 
4046   /* A lambda might use a parameter pack from the containing context.  */
4047   if (current_class_type && LAMBDA_TYPE_P (current_class_type)
4048       && CLASSTYPE_TEMPLATE_INFO (current_class_type))
4049     return false;
4050 
4051   if (TREE_CODE (t) == TYPE_DECL)
4052     t = TREE_TYPE (t);
4053 
4054   ppd.parameter_packs = &parameter_packs;
4055   ppd.visited = new hash_set<tree>;
4056   ppd.type_pack_expansion_p = false;
4057   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4058   delete ppd.visited;
4059 
4060   if (parameter_packs)
4061     {
4062       location_t loc = EXPR_LOC_OR_LOC (t, input_location);
4063       error_at (loc, "parameter packs not expanded with %<...%>:");
4064       while (parameter_packs)
4065         {
4066           tree pack = TREE_VALUE (parameter_packs);
4067           tree name = NULL_TREE;
4068 
4069           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4070               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4071             name = TYPE_NAME (pack);
4072           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4073             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4074 	  else if (TREE_CODE (pack) == CALL_EXPR)
4075 	    name = DECL_NAME (CALL_EXPR_FN (pack));
4076           else
4077             name = DECL_NAME (pack);
4078 
4079 	  if (name)
4080 	    inform (loc, "        %qD", name);
4081 	  else
4082 	    inform (loc, "        <anonymous>");
4083 
4084           parameter_packs = TREE_CHAIN (parameter_packs);
4085         }
4086 
4087       return true;
4088     }
4089 
4090   return false;
4091 }
4092 
4093 /* Expand any parameter packs that occur in the template arguments in
4094    ARGS.  */
4095 tree
4096 expand_template_argument_pack (tree args)
4097 {
4098   if (args == error_mark_node)
4099     return error_mark_node;
4100 
4101   tree result_args = NULL_TREE;
4102   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4103   int num_result_args = -1;
4104   int non_default_args_count = -1;
4105 
4106   /* First, determine if we need to expand anything, and the number of
4107      slots we'll need.  */
4108   for (in_arg = 0; in_arg < nargs; ++in_arg)
4109     {
4110       tree arg = TREE_VEC_ELT (args, in_arg);
4111       if (arg == NULL_TREE)
4112 	return args;
4113       if (ARGUMENT_PACK_P (arg))
4114         {
4115           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4116           if (num_result_args < 0)
4117             num_result_args = in_arg + num_packed;
4118           else
4119             num_result_args += num_packed;
4120         }
4121       else
4122         {
4123           if (num_result_args >= 0)
4124             num_result_args++;
4125         }
4126     }
4127 
4128   /* If no expansion is necessary, we're done.  */
4129   if (num_result_args < 0)
4130     return args;
4131 
4132   /* Expand arguments.  */
4133   result_args = make_tree_vec (num_result_args);
4134   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4135     non_default_args_count =
4136       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4137   for (in_arg = 0; in_arg < nargs; ++in_arg)
4138     {
4139       tree arg = TREE_VEC_ELT (args, in_arg);
4140       if (ARGUMENT_PACK_P (arg))
4141         {
4142           tree packed = ARGUMENT_PACK_ARGS (arg);
4143           int i, num_packed = TREE_VEC_LENGTH (packed);
4144           for (i = 0; i < num_packed; ++i, ++out_arg)
4145             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4146 	  if (non_default_args_count > 0)
4147 	    non_default_args_count += num_packed - 1;
4148         }
4149       else
4150         {
4151           TREE_VEC_ELT (result_args, out_arg) = arg;
4152           ++out_arg;
4153         }
4154     }
4155   if (non_default_args_count >= 0)
4156     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4157   return result_args;
4158 }
4159 
4160 /* Checks if DECL shadows a template parameter.
4161 
4162    [temp.local]: A template-parameter shall not be redeclared within its
4163    scope (including nested scopes).
4164 
4165    Emits an error and returns TRUE if the DECL shadows a parameter,
4166    returns FALSE otherwise.  */
4167 
4168 bool
4169 check_template_shadow (tree decl)
4170 {
4171   tree olddecl;
4172 
4173   /* If we're not in a template, we can't possibly shadow a template
4174      parameter.  */
4175   if (!current_template_parms)
4176     return true;
4177 
4178   /* Figure out what we're shadowing.  */
4179   decl = OVL_FIRST (decl);
4180   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4181 
4182   /* If there's no previous binding for this name, we're not shadowing
4183      anything, let alone a template parameter.  */
4184   if (!olddecl)
4185     return true;
4186 
4187   /* If we're not shadowing a template parameter, we're done.  Note
4188      that OLDDECL might be an OVERLOAD (or perhaps even an
4189      ERROR_MARK), so we can't just blithely assume it to be a _DECL
4190      node.  */
4191   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4192     return true;
4193 
4194   /* We check for decl != olddecl to avoid bogus errors for using a
4195      name inside a class.  We check TPFI to avoid duplicate errors for
4196      inline member templates.  */
4197   if (decl == olddecl
4198       || (DECL_TEMPLATE_PARM_P (decl)
4199 	  && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4200     return true;
4201 
4202   /* Don't complain about the injected class name, as we've already
4203      complained about the class itself.  */
4204   if (DECL_SELF_REFERENCE_P (decl))
4205     return false;
4206 
4207   if (DECL_TEMPLATE_PARM_P (decl))
4208     error ("declaration of template parameter %q+D shadows "
4209 	   "template parameter", decl);
4210   else
4211     error ("declaration of %q+#D shadows template parameter", decl);
4212   inform (DECL_SOURCE_LOCATION (olddecl),
4213 	  "template parameter %qD declared here", olddecl);
4214   return false;
4215 }
4216 
4217 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4218    ORIG_LEVEL, DECL, and TYPE.  */
4219 
4220 static tree
4221 build_template_parm_index (int index,
4222 			   int level,
4223 			   int orig_level,
4224 			   tree decl,
4225 			   tree type)
4226 {
4227   tree t = make_node (TEMPLATE_PARM_INDEX);
4228   TEMPLATE_PARM_IDX (t) = index;
4229   TEMPLATE_PARM_LEVEL (t) = level;
4230   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4231   TEMPLATE_PARM_DECL (t) = decl;
4232   TREE_TYPE (t) = type;
4233   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4234   TREE_READONLY (t) = TREE_READONLY (decl);
4235 
4236   return t;
4237 }
4238 
4239 /* Find the canonical type parameter for the given template type
4240    parameter.  Returns the canonical type parameter, which may be TYPE
4241    if no such parameter existed.  */
4242 
4243 static tree
4244 canonical_type_parameter (tree type)
4245 {
4246   tree list;
4247   int idx = TEMPLATE_TYPE_IDX (type);
4248   if (!canonical_template_parms)
4249     vec_alloc (canonical_template_parms, idx + 1);
4250 
4251   if (canonical_template_parms->length () <= (unsigned) idx)
4252     vec_safe_grow_cleared (canonical_template_parms, idx + 1);
4253 
4254   list = (*canonical_template_parms)[idx];
4255   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4256     list = TREE_CHAIN (list);
4257 
4258   if (list)
4259     return TREE_VALUE (list);
4260   else
4261     {
4262       (*canonical_template_parms)[idx]
4263 	= tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4264       return type;
4265     }
4266 }
4267 
4268 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4269    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
4270    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4271    new one is created.  */
4272 
4273 static tree
4274 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4275 			    tsubst_flags_t complain)
4276 {
4277   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4278       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4279 	  != TEMPLATE_PARM_LEVEL (index) - levels)
4280       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4281     {
4282       tree orig_decl = TEMPLATE_PARM_DECL (index);
4283       tree decl, t;
4284 
4285       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4286 			 TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
4287       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4288       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4289       DECL_ARTIFICIAL (decl) = 1;
4290       SET_DECL_TEMPLATE_PARM_P (decl);
4291 
4292       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4293 				     TEMPLATE_PARM_LEVEL (index) - levels,
4294 				     TEMPLATE_PARM_ORIG_LEVEL (index),
4295 				     decl, type);
4296       TEMPLATE_PARM_DESCENDANTS (index) = t;
4297       TEMPLATE_PARM_PARAMETER_PACK (t)
4298 	= TEMPLATE_PARM_PARAMETER_PACK (index);
4299 
4300 	/* Template template parameters need this.  */
4301       if (TREE_CODE (decl) == TEMPLATE_DECL)
4302 	{
4303 	  DECL_TEMPLATE_RESULT (decl)
4304 	    = build_decl (DECL_SOURCE_LOCATION (decl),
4305 			  TYPE_DECL, DECL_NAME (decl), type);
4306 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (decl)) = true;
4307 	  DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4308 	    (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4309 	}
4310     }
4311 
4312   return TEMPLATE_PARM_DESCENDANTS (index);
4313 }
4314 
4315 /* Process information from new template parameter PARM and append it
4316    to the LIST being built.  This new parameter is a non-type
4317    parameter iff IS_NON_TYPE is true. This new parameter is a
4318    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4319    is in PARM_LOC.  */
4320 
4321 tree
4322 process_template_parm (tree list, location_t parm_loc, tree parm,
4323 		       bool is_non_type, bool is_parameter_pack)
4324 {
4325   tree decl = 0;
4326   int idx = 0;
4327 
4328   gcc_assert (TREE_CODE (parm) == TREE_LIST);
4329   tree defval = TREE_PURPOSE (parm);
4330   tree constr = TREE_TYPE (parm);
4331 
4332   if (list)
4333     {
4334       tree p = tree_last (list);
4335 
4336       if (p && TREE_VALUE (p) != error_mark_node)
4337         {
4338           p = TREE_VALUE (p);
4339           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4340             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4341           else
4342             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4343         }
4344 
4345       ++idx;
4346     }
4347 
4348   if (is_non_type)
4349     {
4350       parm = TREE_VALUE (parm);
4351 
4352       SET_DECL_TEMPLATE_PARM_P (parm);
4353 
4354       if (TREE_TYPE (parm) != error_mark_node)
4355 	{
4356 	  /* [temp.param]
4357 
4358 	     The top-level cv-qualifiers on the template-parameter are
4359 	     ignored when determining its type.  */
4360 	  TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4361 	  if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4362 	    TREE_TYPE (parm) = error_mark_node;
4363 	  else if (uses_parameter_packs (TREE_TYPE (parm))
4364 		   && !is_parameter_pack
4365 		   /* If we're in a nested template parameter list, the template
4366 		      template parameter could be a parameter pack.  */
4367 		   && processing_template_parmlist == 1)
4368 	    {
4369 	      /* This template parameter is not a parameter pack, but it
4370 		 should be. Complain about "bare" parameter packs.  */
4371 	      check_for_bare_parameter_packs (TREE_TYPE (parm));
4372 
4373 	      /* Recover by calling this a parameter pack.  */
4374 	      is_parameter_pack = true;
4375 	    }
4376 	}
4377 
4378       /* A template parameter is not modifiable.  */
4379       TREE_CONSTANT (parm) = 1;
4380       TREE_READONLY (parm) = 1;
4381       decl = build_decl (parm_loc,
4382 			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4383       TREE_CONSTANT (decl) = 1;
4384       TREE_READONLY (decl) = 1;
4385       DECL_INITIAL (parm) = DECL_INITIAL (decl)
4386 	= build_template_parm_index (idx, processing_template_decl,
4387 				     processing_template_decl,
4388 				     decl, TREE_TYPE (parm));
4389 
4390       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4391 	= is_parameter_pack;
4392     }
4393   else
4394     {
4395       tree t;
4396       parm = TREE_VALUE (TREE_VALUE (parm));
4397 
4398       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4399 	{
4400 	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4401 	  /* This is for distinguishing between real templates and template
4402 	     template parameters */
4403 	  TREE_TYPE (parm) = t;
4404 	  TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
4405 	  decl = parm;
4406 	}
4407       else
4408 	{
4409 	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
4410 	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4411 	  decl = build_decl (parm_loc,
4412 			     TYPE_DECL, parm, t);
4413 	}
4414 
4415       TYPE_NAME (t) = decl;
4416       TYPE_STUB_DECL (t) = decl;
4417       parm = decl;
4418       TEMPLATE_TYPE_PARM_INDEX (t)
4419 	= build_template_parm_index (idx, processing_template_decl,
4420 				     processing_template_decl,
4421 				     decl, TREE_TYPE (parm));
4422       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4423       TYPE_CANONICAL (t) = canonical_type_parameter (t);
4424     }
4425   DECL_ARTIFICIAL (decl) = 1;
4426   SET_DECL_TEMPLATE_PARM_P (decl);
4427 
4428   /* Build requirements for the type/template parameter.
4429      This must be done after SET_DECL_TEMPLATE_PARM_P or
4430      process_template_parm could fail. */
4431   tree reqs = finish_shorthand_constraint (parm, constr);
4432 
4433   pushdecl (decl);
4434 
4435   if (defval && TREE_CODE (defval) == OVERLOAD)
4436     lookup_keep (defval, true);
4437 
4438   /* Build the parameter node linking the parameter declaration,
4439      its default argument (if any), and its constraints (if any). */
4440   parm = build_tree_list (defval, parm);
4441   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4442 
4443   return chainon (list, parm);
4444 }
4445 
4446 /* The end of a template parameter list has been reached.  Process the
4447    tree list into a parameter vector, converting each parameter into a more
4448    useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
4449    as PARM_DECLs.  */
4450 
4451 tree
4452 end_template_parm_list (tree parms)
4453 {
4454   int nparms;
4455   tree parm, next;
4456   tree saved_parmlist = make_tree_vec (list_length (parms));
4457 
4458   /* Pop the dummy parameter level and add the real one.  */
4459   current_template_parms = TREE_CHAIN (current_template_parms);
4460 
4461   current_template_parms
4462     = tree_cons (size_int (processing_template_decl),
4463 		 saved_parmlist, current_template_parms);
4464 
4465   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
4466     {
4467       next = TREE_CHAIN (parm);
4468       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
4469       TREE_CHAIN (parm) = NULL_TREE;
4470     }
4471 
4472   --processing_template_parmlist;
4473 
4474   return saved_parmlist;
4475 }
4476 
4477 // Explicitly indicate the end of the template parameter list. We assume
4478 // that the current template parameters have been constructed and/or
4479 // managed explicitly, as when creating new template template parameters
4480 // from a shorthand constraint.
4481 void
4482 end_template_parm_list ()
4483 {
4484   --processing_template_parmlist;
4485 }
4486 
4487 /* end_template_decl is called after a template declaration is seen.  */
4488 
4489 void
4490 end_template_decl (void)
4491 {
4492   reset_specialization ();
4493 
4494   if (! processing_template_decl)
4495     return;
4496 
4497   /* This matches the pushlevel in begin_template_parm_list.  */
4498   finish_scope ();
4499 
4500   --processing_template_decl;
4501   current_template_parms = TREE_CHAIN (current_template_parms);
4502 }
4503 
4504 /* Takes a TREE_LIST representing a template parameter and convert it
4505    into an argument suitable to be passed to the type substitution
4506    functions.  Note that If the TREE_LIST contains an error_mark
4507    node, the returned argument is error_mark_node.  */
4508 
4509 tree
4510 template_parm_to_arg (tree t)
4511 {
4512 
4513   if (t == NULL_TREE
4514       || TREE_CODE (t) != TREE_LIST)
4515     return t;
4516 
4517   if (error_operand_p (TREE_VALUE (t)))
4518     return error_mark_node;
4519 
4520   t = TREE_VALUE (t);
4521 
4522   if (TREE_CODE (t) == TYPE_DECL
4523       || TREE_CODE (t) == TEMPLATE_DECL)
4524     {
4525       t = TREE_TYPE (t);
4526 
4527       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4528 	{
4529 	  /* Turn this argument into a TYPE_ARGUMENT_PACK
4530 	     with a single element, which expands T.  */
4531 	  tree vec = make_tree_vec (1);
4532 	  if (CHECKING_P)
4533 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4534 
4535 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4536 
4537 	  t = cxx_make_type (TYPE_ARGUMENT_PACK);
4538 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4539 	}
4540     }
4541   else
4542     {
4543       t = DECL_INITIAL (t);
4544 
4545       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4546 	{
4547 	  /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4548 	     with a single element, which expands T.  */
4549 	  tree vec = make_tree_vec (1);
4550 	  if (CHECKING_P)
4551 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4552 
4553 	  t = convert_from_reference (t);
4554 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4555 
4556 	  t  = make_node (NONTYPE_ARGUMENT_PACK);
4557 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4558 	}
4559       else
4560 	t = convert_from_reference (t);
4561     }
4562   return t;
4563 }
4564 
4565 /* Given a single level of template parameters (a TREE_VEC), return it
4566    as a set of template arguments.  */
4567 
4568 static tree
4569 template_parms_level_to_args (tree parms)
4570 {
4571   tree a = copy_node (parms);
4572   TREE_TYPE (a) = NULL_TREE;
4573   for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4574     TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4575 
4576   if (CHECKING_P)
4577     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4578 
4579   return a;
4580 }
4581 
4582 /* Given a set of template parameters, return them as a set of template
4583    arguments.  The template parameters are represented as a TREE_VEC, in
4584    the form documented in cp-tree.h for template arguments.  */
4585 
4586 static tree
4587 template_parms_to_args (tree parms)
4588 {
4589   tree header;
4590   tree args = NULL_TREE;
4591   int length = TMPL_PARMS_DEPTH (parms);
4592   int l = length;
4593 
4594   /* If there is only one level of template parameters, we do not
4595      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4596      TREE_VEC containing the arguments.  */
4597   if (length > 1)
4598     args = make_tree_vec (length);
4599 
4600   for (header = parms; header; header = TREE_CHAIN (header))
4601     {
4602       tree a = template_parms_level_to_args (TREE_VALUE (header));
4603 
4604       if (length > 1)
4605 	TREE_VEC_ELT (args, --l) = a;
4606       else
4607 	args = a;
4608     }
4609 
4610   return args;
4611 }
4612 
4613 /* Within the declaration of a template, return the currently active
4614    template parameters as an argument TREE_VEC.  */
4615 
4616 static tree
4617 current_template_args (void)
4618 {
4619   return template_parms_to_args (current_template_parms);
4620 }
4621 
4622 /* Update the declared TYPE by doing any lookups which were thought to be
4623    dependent, but are not now that we know the SCOPE of the declarator.  */
4624 
4625 tree
4626 maybe_update_decl_type (tree orig_type, tree scope)
4627 {
4628   tree type = orig_type;
4629 
4630   if (type == NULL_TREE)
4631     return type;
4632 
4633   if (TREE_CODE (orig_type) == TYPE_DECL)
4634     type = TREE_TYPE (type);
4635 
4636   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4637       && dependent_type_p (type)
4638       /* Don't bother building up the args in this case.  */
4639       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4640     {
4641       /* tsubst in the args corresponding to the template parameters,
4642 	 including auto if present.  Most things will be unchanged, but
4643 	 make_typename_type and tsubst_qualified_id will resolve
4644 	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4645       tree args = current_template_args ();
4646       tree auto_node = type_uses_auto (type);
4647       tree pushed;
4648       if (auto_node)
4649 	{
4650 	  tree auto_vec = make_tree_vec (1);
4651 	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
4652 	  args = add_to_template_args (args, auto_vec);
4653 	}
4654       pushed = push_scope (scope);
4655       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4656       if (pushed)
4657 	pop_scope (scope);
4658     }
4659 
4660   if (type == error_mark_node)
4661     return orig_type;
4662 
4663   if (TREE_CODE (orig_type) == TYPE_DECL)
4664     {
4665       if (same_type_p (type, TREE_TYPE (orig_type)))
4666 	type = orig_type;
4667       else
4668 	type = TYPE_NAME (type);
4669     }
4670   return type;
4671 }
4672 
4673 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4674    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
4675    the new  template is a member template. */
4676 
4677 tree
4678 build_template_decl (tree decl, tree parms, bool member_template_p)
4679 {
4680   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4681   SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
4682   DECL_TEMPLATE_PARMS (tmpl) = parms;
4683   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4684   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4685   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4686 
4687   return tmpl;
4688 }
4689 
4690 struct template_parm_data
4691 {
4692   /* The level of the template parameters we are currently
4693      processing.  */
4694   int level;
4695 
4696   /* The index of the specialization argument we are currently
4697      processing.  */
4698   int current_arg;
4699 
4700   /* An array whose size is the number of template parameters.  The
4701      elements are nonzero if the parameter has been used in any one
4702      of the arguments processed so far.  */
4703   int* parms;
4704 
4705   /* An array whose size is the number of template arguments.  The
4706      elements are nonzero if the argument makes use of template
4707      parameters of this level.  */
4708   int* arg_uses_template_parms;
4709 };
4710 
4711 /* Subroutine of push_template_decl used to see if each template
4712    parameter in a partial specialization is used in the explicit
4713    argument list.  If T is of the LEVEL given in DATA (which is
4714    treated as a template_parm_data*), then DATA->PARMS is marked
4715    appropriately.  */
4716 
4717 static int
4718 mark_template_parm (tree t, void* data)
4719 {
4720   int level;
4721   int idx;
4722   struct template_parm_data* tpd = (struct template_parm_data*) data;
4723 
4724   template_parm_level_and_index (t, &level, &idx);
4725 
4726   if (level == tpd->level)
4727     {
4728       tpd->parms[idx] = 1;
4729       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4730     }
4731 
4732   /* In C++17 the type of a non-type argument is a deduced context.  */
4733   if (cxx_dialect >= cxx17
4734       && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4735     for_each_template_parm (TREE_TYPE (t),
4736 			    &mark_template_parm,
4737 			    data,
4738 			    NULL,
4739 			    /*include_nondeduced_p=*/false);
4740 
4741   /* Return zero so that for_each_template_parm will continue the
4742      traversal of the tree; we want to mark *every* template parm.  */
4743   return 0;
4744 }
4745 
4746 /* Process the partial specialization DECL.  */
4747 
4748 static tree
4749 process_partial_specialization (tree decl)
4750 {
4751   tree type = TREE_TYPE (decl);
4752   tree tinfo = get_template_info (decl);
4753   tree maintmpl = TI_TEMPLATE (tinfo);
4754   tree specargs = TI_ARGS (tinfo);
4755   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4756   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4757   tree inner_parms;
4758   tree inst;
4759   int nargs = TREE_VEC_LENGTH (inner_args);
4760   int ntparms;
4761   int  i;
4762   bool did_error_intro = false;
4763   struct template_parm_data tpd;
4764   struct template_parm_data tpd2;
4765 
4766   gcc_assert (current_template_parms);
4767 
4768   /* A concept cannot be specialized.  */
4769   if (flag_concepts && variable_concept_p (maintmpl))
4770     {
4771       error ("specialization of variable concept %q#D", maintmpl);
4772       return error_mark_node;
4773     }
4774 
4775   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4776   ntparms = TREE_VEC_LENGTH (inner_parms);
4777 
4778   /* We check that each of the template parameters given in the
4779      partial specialization is used in the argument list to the
4780      specialization.  For example:
4781 
4782        template <class T> struct S;
4783        template <class T> struct S<T*>;
4784 
4785      The second declaration is OK because `T*' uses the template
4786      parameter T, whereas
4787 
4788        template <class T> struct S<int>;
4789 
4790      is no good.  Even trickier is:
4791 
4792        template <class T>
4793        struct S1
4794        {
4795 	  template <class U>
4796 	  struct S2;
4797 	  template <class U>
4798 	  struct S2<T>;
4799        };
4800 
4801      The S2<T> declaration is actually invalid; it is a
4802      full-specialization.  Of course,
4803 
4804 	  template <class U>
4805 	  struct S2<T (*)(U)>;
4806 
4807      or some such would have been OK.  */
4808   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4809   tpd.parms = XALLOCAVEC (int, ntparms);
4810   memset (tpd.parms, 0, sizeof (int) * ntparms);
4811 
4812   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4813   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4814   for (i = 0; i < nargs; ++i)
4815     {
4816       tpd.current_arg = i;
4817       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4818 			      &mark_template_parm,
4819 			      &tpd,
4820 			      NULL,
4821 			      /*include_nondeduced_p=*/false);
4822     }
4823   for (i = 0; i < ntparms; ++i)
4824     if (tpd.parms[i] == 0)
4825       {
4826 	/* One of the template parms was not used in a deduced context in the
4827 	   specialization.  */
4828 	if (!did_error_intro)
4829 	  {
4830 	    error ("template parameters not deducible in "
4831 		   "partial specialization:");
4832 	    did_error_intro = true;
4833 	  }
4834 
4835 	inform (input_location, "        %qD",
4836 		TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4837       }
4838 
4839   if (did_error_intro)
4840     return error_mark_node;
4841 
4842   /* [temp.class.spec]
4843 
4844      The argument list of the specialization shall not be identical to
4845      the implicit argument list of the primary template.  */
4846   tree main_args
4847     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
4848   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
4849       && (!flag_concepts
4850 	  || !strictly_subsumes (current_template_constraints (),
4851 				 get_constraints (maintmpl))))
4852     {
4853       if (!flag_concepts)
4854         error ("partial specialization %q+D does not specialize "
4855 	       "any template arguments; to define the primary template, "
4856 	       "remove the template argument list", decl);
4857       else
4858         error ("partial specialization %q+D does not specialize any "
4859 	       "template arguments and is not more constrained than "
4860 	       "the primary template; to define the primary template, "
4861 	       "remove the template argument list", decl);
4862       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4863     }
4864 
4865   /* A partial specialization that replaces multiple parameters of the
4866      primary template with a pack expansion is less specialized for those
4867      parameters.  */
4868   if (nargs < DECL_NTPARMS (maintmpl))
4869     {
4870       error ("partial specialization is not more specialized than the "
4871 	     "primary template because it replaces multiple parameters "
4872 	     "with a pack expansion");
4873       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4874       /* Avoid crash in process_partial_specialization.  */
4875       return decl;
4876     }
4877 
4878   /* If we aren't in a dependent class, we can actually try deduction.  */
4879   else if (tpd.level == 1
4880 	   /* FIXME we should be able to handle a partial specialization of a
4881 	      partial instantiation, but currently we can't (c++/41727).  */
4882 	   && TMPL_ARGS_DEPTH (specargs) == 1
4883 	   && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
4884     {
4885       if (permerror (input_location, "partial specialization %qD is not "
4886 		     "more specialized than", decl))
4887 	inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
4888 		maintmpl);
4889     }
4890 
4891   /* [temp.class.spec]
4892 
4893      A partially specialized non-type argument expression shall not
4894      involve template parameters of the partial specialization except
4895      when the argument expression is a simple identifier.
4896 
4897      The type of a template parameter corresponding to a specialized
4898      non-type argument shall not be dependent on a parameter of the
4899      specialization.
4900 
4901      Also, we verify that pack expansions only occur at the
4902      end of the argument list.  */
4903   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4904   tpd2.parms = 0;
4905   for (i = 0; i < nargs; ++i)
4906     {
4907       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4908       tree arg = TREE_VEC_ELT (inner_args, i);
4909       tree packed_args = NULL_TREE;
4910       int j, len = 1;
4911 
4912       if (ARGUMENT_PACK_P (arg))
4913         {
4914           /* Extract the arguments from the argument pack. We'll be
4915              iterating over these in the following loop.  */
4916           packed_args = ARGUMENT_PACK_ARGS (arg);
4917           len = TREE_VEC_LENGTH (packed_args);
4918         }
4919 
4920       for (j = 0; j < len; j++)
4921         {
4922           if (packed_args)
4923             /* Get the Jth argument in the parameter pack.  */
4924             arg = TREE_VEC_ELT (packed_args, j);
4925 
4926           if (PACK_EXPANSION_P (arg))
4927             {
4928               /* Pack expansions must come at the end of the
4929                  argument list.  */
4930               if ((packed_args && j < len - 1)
4931                   || (!packed_args && i < nargs - 1))
4932                 {
4933                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4934                     error ("parameter pack argument %qE must be at the "
4935 			   "end of the template argument list", arg);
4936                   else
4937                     error ("parameter pack argument %qT must be at the "
4938 			   "end of the template argument list", arg);
4939                 }
4940             }
4941 
4942           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4943             /* We only care about the pattern.  */
4944             arg = PACK_EXPANSION_PATTERN (arg);
4945 
4946           if (/* These first two lines are the `non-type' bit.  */
4947               !TYPE_P (arg)
4948               && TREE_CODE (arg) != TEMPLATE_DECL
4949               /* This next two lines are the `argument expression is not just a
4950                  simple identifier' condition and also the `specialized
4951                  non-type argument' bit.  */
4952               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
4953 	      && !(REFERENCE_REF_P (arg)
4954 		   && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
4955             {
4956               if ((!packed_args && tpd.arg_uses_template_parms[i])
4957                   || (packed_args && uses_template_parms (arg)))
4958                 error ("template argument %qE involves template parameter(s)",
4959                        arg);
4960               else
4961                 {
4962                   /* Look at the corresponding template parameter,
4963                      marking which template parameters its type depends
4964                      upon.  */
4965                   tree type = TREE_TYPE (parm);
4966 
4967                   if (!tpd2.parms)
4968                     {
4969                       /* We haven't yet initialized TPD2.  Do so now.  */
4970                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4971                       /* The number of parameters here is the number in the
4972                          main template, which, as checked in the assertion
4973                          above, is NARGS.  */
4974                       tpd2.parms = XALLOCAVEC (int, nargs);
4975                       tpd2.level =
4976                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4977                     }
4978 
4979                   /* Mark the template parameters.  But this time, we're
4980                      looking for the template parameters of the main
4981                      template, not in the specialization.  */
4982                   tpd2.current_arg = i;
4983                   tpd2.arg_uses_template_parms[i] = 0;
4984                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4985                   for_each_template_parm (type,
4986                                           &mark_template_parm,
4987                                           &tpd2,
4988                                           NULL,
4989 					  /*include_nondeduced_p=*/false);
4990 
4991                   if (tpd2.arg_uses_template_parms [i])
4992                     {
4993                       /* The type depended on some template parameters.
4994                          If they are fully specialized in the
4995                          specialization, that's OK.  */
4996                       int j;
4997                       int count = 0;
4998                       for (j = 0; j < nargs; ++j)
4999                         if (tpd2.parms[j] != 0
5000                             && tpd.arg_uses_template_parms [j])
5001                           ++count;
5002                       if (count != 0)
5003                         error_n (input_location, count,
5004                                  "type %qT of template argument %qE depends "
5005                                  "on a template parameter",
5006                                  "type %qT of template argument %qE depends "
5007                                  "on template parameters",
5008                                  type,
5009                                  arg);
5010                     }
5011                 }
5012             }
5013         }
5014     }
5015 
5016   /* We should only get here once.  */
5017   if (TREE_CODE (decl) == TYPE_DECL)
5018     gcc_assert (!COMPLETE_TYPE_P (type));
5019 
5020   // Build the template decl.
5021   tree tmpl = build_template_decl (decl, current_template_parms,
5022 				   DECL_MEMBER_TEMPLATE_P (maintmpl));
5023   TREE_TYPE (tmpl) = type;
5024   DECL_TEMPLATE_RESULT (tmpl) = decl;
5025   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5026   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5027   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5028 
5029   /* Give template template parms a DECL_CONTEXT of the template
5030      for which they are a parameter.  */
5031   for (i = 0; i < ntparms; ++i)
5032     {
5033       tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5034       if (TREE_CODE (parm) == TEMPLATE_DECL)
5035 	DECL_CONTEXT (parm) = tmpl;
5036     }
5037 
5038   if (VAR_P (decl))
5039     /* We didn't register this in check_explicit_specialization so we could
5040        wait until the constraints were set.  */
5041     decl = register_specialization (decl, maintmpl, specargs, false, 0);
5042   else
5043     associate_classtype_constraints (type);
5044 
5045   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5046     = tree_cons (specargs, tmpl,
5047                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5048   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5049 
5050   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5051        inst = TREE_CHAIN (inst))
5052     {
5053       tree instance = TREE_VALUE (inst);
5054       if (TYPE_P (instance)
5055 	  ? (COMPLETE_TYPE_P (instance)
5056 	     && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5057 	  : DECL_TEMPLATE_INSTANTIATION (instance))
5058 	{
5059 	  tree spec = most_specialized_partial_spec (instance, tf_none);
5060 	  tree inst_decl = (DECL_P (instance)
5061 			    ? instance : TYPE_NAME (instance));
5062 	  if (!spec)
5063 	    /* OK */;
5064 	  else if (spec == error_mark_node)
5065 	    permerror (input_location,
5066 		       "declaration of %qD ambiguates earlier template "
5067 		       "instantiation for %qD", decl, inst_decl);
5068 	  else if (TREE_VALUE (spec) == tmpl)
5069 	    permerror (input_location,
5070 		       "partial specialization of %qD after instantiation "
5071 		       "of %qD", decl, inst_decl);
5072 	}
5073     }
5074 
5075   return decl;
5076 }
5077 
5078 /* PARM is a template parameter of some form; return the corresponding
5079    TEMPLATE_PARM_INDEX.  */
5080 
5081 static tree
5082 get_template_parm_index (tree parm)
5083 {
5084   if (TREE_CODE (parm) == PARM_DECL
5085       || TREE_CODE (parm) == CONST_DECL)
5086     parm = DECL_INITIAL (parm);
5087   else if (TREE_CODE (parm) == TYPE_DECL
5088 	   || TREE_CODE (parm) == TEMPLATE_DECL)
5089     parm = TREE_TYPE (parm);
5090   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5091       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5092       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5093     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5094   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5095   return parm;
5096 }
5097 
5098 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
5099    parameter packs used by the template parameter PARM.  */
5100 
5101 static void
5102 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5103 {
5104   /* A type parm can't refer to another parm.  */
5105   if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5106     return;
5107   else if (TREE_CODE (parm) == PARM_DECL)
5108     {
5109       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5110 		    ppd, ppd->visited);
5111       return;
5112     }
5113 
5114   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5115 
5116   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5117   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5118     fixed_parameter_pack_p_1 (TREE_VALUE (TREE_VEC_ELT (vec, i)), ppd);
5119 }
5120 
5121 /* PARM is a template parameter pack.  Return any parameter packs used in
5122    its type or the type of any of its template parameters.  If there are
5123    any such packs, it will be instantiated into a fixed template parameter
5124    list by partial instantiation rather than be fully deduced.  */
5125 
5126 tree
5127 fixed_parameter_pack_p (tree parm)
5128 {
5129   /* This can only be true in a member template.  */
5130   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5131     return NULL_TREE;
5132   /* This can only be true for a parameter pack.  */
5133   if (!template_parameter_pack_p (parm))
5134     return NULL_TREE;
5135   /* A type parm can't refer to another parm.  */
5136   if (TREE_CODE (parm) == TYPE_DECL)
5137     return NULL_TREE;
5138 
5139   tree parameter_packs = NULL_TREE;
5140   struct find_parameter_pack_data ppd;
5141   ppd.parameter_packs = &parameter_packs;
5142   ppd.visited = new hash_set<tree>;
5143   ppd.type_pack_expansion_p = false;
5144 
5145   fixed_parameter_pack_p_1 (parm, &ppd);
5146 
5147   delete ppd.visited;
5148   return parameter_packs;
5149 }
5150 
5151 /* Check that a template declaration's use of default arguments and
5152    parameter packs is not invalid.  Here, PARMS are the template
5153    parameters.  IS_PRIMARY is true if DECL is the thing declared by
5154    a primary template.  IS_PARTIAL is true if DECL is a partial
5155    specialization.
5156 
5157    IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5158    function template declaration or a friend class template
5159    declaration.  In the function case, 1 indicates a declaration, 2
5160    indicates a redeclaration.  When IS_FRIEND_DECL=2, no errors are
5161    emitted for extraneous default arguments.
5162 
5163    Returns TRUE if there were no errors found, FALSE otherwise. */
5164 
5165 bool
5166 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5167                          bool is_partial, int is_friend_decl)
5168 {
5169   const char *msg;
5170   int last_level_to_check;
5171   tree parm_level;
5172   bool no_errors = true;
5173 
5174   /* [temp.param]
5175 
5176      A default template-argument shall not be specified in a
5177      function template declaration or a function template definition, nor
5178      in the template-parameter-list of the definition of a member of a
5179      class template.  */
5180 
5181   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5182       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
5183     /* You can't have a function template declaration in a local
5184        scope, nor you can you define a member of a class template in a
5185        local scope.  */
5186     return true;
5187 
5188   if ((TREE_CODE (decl) == TYPE_DECL
5189        && TREE_TYPE (decl)
5190        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5191       || (TREE_CODE (decl) == FUNCTION_DECL
5192 	  && LAMBDA_FUNCTION_P (decl)))
5193     /* A lambda doesn't have an explicit declaration; don't complain
5194        about the parms of the enclosing class.  */
5195     return true;
5196 
5197   if (current_class_type
5198       && !TYPE_BEING_DEFINED (current_class_type)
5199       && DECL_LANG_SPECIFIC (decl)
5200       && DECL_DECLARES_FUNCTION_P (decl)
5201       /* If this is either a friend defined in the scope of the class
5202 	 or a member function.  */
5203       && (DECL_FUNCTION_MEMBER_P (decl)
5204 	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5205 	  : DECL_FRIEND_CONTEXT (decl)
5206 	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5207 	  : false)
5208       /* And, if it was a member function, it really was defined in
5209 	 the scope of the class.  */
5210       && (!DECL_FUNCTION_MEMBER_P (decl)
5211 	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
5212     /* We already checked these parameters when the template was
5213        declared, so there's no need to do it again now.  This function
5214        was defined in class scope, but we're processing its body now
5215        that the class is complete.  */
5216     return true;
5217 
5218   /* Core issue 226 (C++0x only): the following only applies to class
5219      templates.  */
5220   if (is_primary
5221       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5222     {
5223       /* [temp.param]
5224 
5225          If a template-parameter has a default template-argument, all
5226          subsequent template-parameters shall have a default
5227          template-argument supplied.  */
5228       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5229         {
5230           tree inner_parms = TREE_VALUE (parm_level);
5231           int ntparms = TREE_VEC_LENGTH (inner_parms);
5232           int seen_def_arg_p = 0;
5233           int i;
5234 
5235           for (i = 0; i < ntparms; ++i)
5236             {
5237               tree parm = TREE_VEC_ELT (inner_parms, i);
5238 
5239               if (parm == error_mark_node)
5240                 continue;
5241 
5242               if (TREE_PURPOSE (parm))
5243                 seen_def_arg_p = 1;
5244               else if (seen_def_arg_p
5245 		       && !template_parameter_pack_p (TREE_VALUE (parm)))
5246                 {
5247                   error ("no default argument for %qD", TREE_VALUE (parm));
5248                   /* For better subsequent error-recovery, we indicate that
5249                      there should have been a default argument.  */
5250                   TREE_PURPOSE (parm) = error_mark_node;
5251                   no_errors = false;
5252                 }
5253 	      else if (!is_partial
5254 		       && !is_friend_decl
5255 		       /* Don't complain about an enclosing partial
5256 			  specialization.  */
5257 		       && parm_level == parms
5258 		       && TREE_CODE (decl) == TYPE_DECL
5259 		       && i < ntparms - 1
5260 		       && template_parameter_pack_p (TREE_VALUE (parm))
5261 		       /* A fixed parameter pack will be partially
5262 			  instantiated into a fixed length list.  */
5263 		       && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5264 		{
5265 		  /* A primary class template can only have one
5266 		     parameter pack, at the end of the template
5267 		     parameter list.  */
5268 
5269 		  error ("parameter pack %q+D must be at the end of the"
5270 			 " template parameter list", TREE_VALUE (parm));
5271 
5272 		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5273 		    = error_mark_node;
5274 		  no_errors = false;
5275 		}
5276             }
5277         }
5278     }
5279 
5280   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5281       || is_partial
5282       || !is_primary
5283       || is_friend_decl)
5284     /* For an ordinary class template, default template arguments are
5285        allowed at the innermost level, e.g.:
5286 	 template <class T = int>
5287 	 struct S {};
5288        but, in a partial specialization, they're not allowed even
5289        there, as we have in [temp.class.spec]:
5290 
5291 	 The template parameter list of a specialization shall not
5292 	 contain default template argument values.
5293 
5294        So, for a partial specialization, or for a function template
5295        (in C++98/C++03), we look at all of them.  */
5296     ;
5297   else
5298     /* But, for a primary class template that is not a partial
5299        specialization we look at all template parameters except the
5300        innermost ones.  */
5301     parms = TREE_CHAIN (parms);
5302 
5303   /* Figure out what error message to issue.  */
5304   if (is_friend_decl == 2)
5305     msg = G_("default template arguments may not be used in function template "
5306 	     "friend re-declaration");
5307   else if (is_friend_decl)
5308     msg = G_("default template arguments may not be used in template "
5309 	     "friend declarations");
5310   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5311     msg = G_("default template arguments may not be used in function templates "
5312 	     "without -std=c++11 or -std=gnu++11");
5313   else if (is_partial)
5314     msg = G_("default template arguments may not be used in "
5315 	     "partial specializations");
5316   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5317     msg = G_("default argument for template parameter for class enclosing %qD");
5318   else
5319     /* Per [temp.param]/9, "A default template-argument shall not be
5320        specified in the template-parameter-lists of the definition of
5321        a member of a class template that appears outside of the member's
5322        class.", thus if we aren't handling a member of a class template
5323        there is no need to examine the parameters.  */
5324     return true;
5325 
5326   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5327     /* If we're inside a class definition, there's no need to
5328        examine the parameters to the class itself.  On the one
5329        hand, they will be checked when the class is defined, and,
5330        on the other, default arguments are valid in things like:
5331 	 template <class T = double>
5332 	 struct S { template <class U> void f(U); };
5333        Here the default argument for `S' has no bearing on the
5334        declaration of `f'.  */
5335     last_level_to_check = template_class_depth (current_class_type) + 1;
5336   else
5337     /* Check everything.  */
5338     last_level_to_check = 0;
5339 
5340   for (parm_level = parms;
5341        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5342        parm_level = TREE_CHAIN (parm_level))
5343     {
5344       tree inner_parms = TREE_VALUE (parm_level);
5345       int i;
5346       int ntparms;
5347 
5348       ntparms = TREE_VEC_LENGTH (inner_parms);
5349       for (i = 0; i < ntparms; ++i)
5350         {
5351           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5352             continue;
5353 
5354 	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5355 	    {
5356 	      if (msg)
5357 	        {
5358                   no_errors = false;
5359                   if (is_friend_decl == 2)
5360                     return no_errors;
5361 
5362 		  error (msg, decl);
5363 		  msg = 0;
5364 	        }
5365 
5366 	      /* Clear out the default argument so that we are not
5367 	         confused later.  */
5368 	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5369 	    }
5370         }
5371 
5372       /* At this point, if we're still interested in issuing messages,
5373 	 they must apply to classes surrounding the object declared.  */
5374       if (msg)
5375 	msg = G_("default argument for template parameter for class "
5376 		 "enclosing %qD");
5377     }
5378 
5379   return no_errors;
5380 }
5381 
5382 /* Worker for push_template_decl_real, called via
5383    for_each_template_parm.  DATA is really an int, indicating the
5384    level of the parameters we are interested in.  If T is a template
5385    parameter of that level, return nonzero.  */
5386 
5387 static int
5388 template_parm_this_level_p (tree t, void* data)
5389 {
5390   int this_level = *(int *)data;
5391   int level;
5392 
5393   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5394     level = TEMPLATE_PARM_LEVEL (t);
5395   else
5396     level = TEMPLATE_TYPE_LEVEL (t);
5397   return level == this_level;
5398 }
5399 
5400 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5401    DATA is really an int, indicating the innermost outer level of parameters.
5402    If T is a template parameter of that level or further out, return
5403    nonzero.  */
5404 
5405 static int
5406 template_parm_outer_level (tree t, void *data)
5407 {
5408   int this_level = *(int *)data;
5409   int level;
5410 
5411   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5412     level = TEMPLATE_PARM_LEVEL (t);
5413   else
5414     level = TEMPLATE_TYPE_LEVEL (t);
5415   return level <= this_level;
5416 }
5417 
5418 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5419    parameters given by current_template_args, or reuses a
5420    previously existing one, if appropriate.  Returns the DECL, or an
5421    equivalent one, if it is replaced via a call to duplicate_decls.
5422 
5423    If IS_FRIEND is true, DECL is a friend declaration.  */
5424 
5425 tree
5426 push_template_decl_real (tree decl, bool is_friend)
5427 {
5428   tree tmpl;
5429   tree args;
5430   tree info;
5431   tree ctx;
5432   bool is_primary;
5433   bool is_partial;
5434   int new_template_p = 0;
5435   /* True if the template is a member template, in the sense of
5436      [temp.mem].  */
5437   bool member_template_p = false;
5438 
5439   if (decl == error_mark_node || !current_template_parms)
5440     return error_mark_node;
5441 
5442   /* See if this is a partial specialization.  */
5443   is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5444 		 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5445 		 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5446 		|| (VAR_P (decl)
5447 		    && DECL_LANG_SPECIFIC (decl)
5448 		    && DECL_TEMPLATE_SPECIALIZATION (decl)
5449 		    && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5450 
5451   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
5452     is_friend = true;
5453 
5454   if (is_friend)
5455     /* For a friend, we want the context of the friend, not
5456        the type of which it is a friend.  */
5457     ctx = CP_DECL_CONTEXT (decl);
5458   else if (CP_DECL_CONTEXT (decl)
5459 	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5460     /* In the case of a virtual function, we want the class in which
5461        it is defined.  */
5462     ctx = CP_DECL_CONTEXT (decl);
5463   else
5464     /* Otherwise, if we're currently defining some class, the DECL
5465        is assumed to be a member of the class.  */
5466     ctx = current_scope ();
5467 
5468   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5469     ctx = NULL_TREE;
5470 
5471   if (!DECL_CONTEXT (decl))
5472     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5473 
5474   /* See if this is a primary template.  */
5475   if (is_friend && ctx
5476       && uses_template_parms_level (ctx, processing_template_decl))
5477     /* A friend template that specifies a class context, i.e.
5478          template <typename T> friend void A<T>::f();
5479        is not primary.  */
5480     is_primary = false;
5481   else if (TREE_CODE (decl) == TYPE_DECL
5482 	   && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5483     is_primary = false;
5484   else
5485     is_primary = template_parm_scope_p ();
5486 
5487   if (is_primary)
5488     {
5489       warning (OPT_Wtemplates, "template %qD declared", decl);
5490 
5491       if (DECL_CLASS_SCOPE_P (decl))
5492 	member_template_p = true;
5493       if (TREE_CODE (decl) == TYPE_DECL
5494 	  && anon_aggrname_p (DECL_NAME (decl)))
5495 	{
5496 	  error ("template class without a name");
5497 	  return error_mark_node;
5498 	}
5499       else if (TREE_CODE (decl) == FUNCTION_DECL)
5500 	{
5501 	  if (member_template_p)
5502 	    {
5503 	      if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5504 		error ("member template %qD may not have virt-specifiers", decl);
5505 	    }
5506 	  if (DECL_DESTRUCTOR_P (decl))
5507 	    {
5508 	      /* [temp.mem]
5509 
5510 		 A destructor shall not be a member template.  */
5511 	      error ("destructor %qD declared as member template", decl);
5512 	      return error_mark_node;
5513 	    }
5514 	  if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5515 	      && (!prototype_p (TREE_TYPE (decl))
5516 		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5517 		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5518 		  || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5519 		      == void_list_node)))
5520 	    {
5521 	      /* [basic.stc.dynamic.allocation]
5522 
5523 		 An allocation function can be a function
5524 		 template. ... Template allocation functions shall
5525 		 have two or more parameters.  */
5526 	      error ("invalid template declaration of %qD", decl);
5527 	      return error_mark_node;
5528 	    }
5529 	}
5530       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5531 	       && CLASS_TYPE_P (TREE_TYPE (decl)))
5532 	{
5533 	  /* Class template, set TEMPLATE_TYPE_PARM_FOR_CLASS.  */
5534 	  tree parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5535 	  for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
5536 	    {
5537 	      tree t = TREE_VALUE (TREE_VEC_ELT (parms, i));
5538 	      if (TREE_CODE (t) == TYPE_DECL)
5539 		t = TREE_TYPE (t);
5540 	      if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
5541 		TEMPLATE_TYPE_PARM_FOR_CLASS (t) = true;
5542 	    }
5543 	}
5544       else if (TREE_CODE (decl) == TYPE_DECL
5545 	       && TYPE_DECL_ALIAS_P (decl))
5546 	/* alias-declaration */
5547 	gcc_assert (!DECL_ARTIFICIAL (decl));
5548       else if (VAR_P (decl))
5549 	/* C++14 variable template. */;
5550       else
5551 	{
5552 	  error ("template declaration of %q#D", decl);
5553 	  return error_mark_node;
5554 	}
5555     }
5556 
5557   /* Check to see that the rules regarding the use of default
5558      arguments are not being violated.  We check args for a friend
5559      functions when we know whether it's a definition, introducing
5560      declaration or re-declaration.  */
5561   if (!is_friend || TREE_CODE (decl) != FUNCTION_DECL)
5562     check_default_tmpl_args (decl, current_template_parms,
5563 			     is_primary, is_partial, is_friend);
5564 
5565   /* Ensure that there are no parameter packs in the type of this
5566      declaration that have not been expanded.  */
5567   if (TREE_CODE (decl) == FUNCTION_DECL)
5568     {
5569       /* Check each of the arguments individually to see if there are
5570          any bare parameter packs.  */
5571       tree type = TREE_TYPE (decl);
5572       tree arg = DECL_ARGUMENTS (decl);
5573       tree argtype = TYPE_ARG_TYPES (type);
5574 
5575       while (arg && argtype)
5576         {
5577           if (!DECL_PACK_P (arg)
5578               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5579             {
5580             /* This is a PARM_DECL that contains unexpanded parameter
5581                packs. We have already complained about this in the
5582                check_for_bare_parameter_packs call, so just replace
5583                these types with ERROR_MARK_NODE.  */
5584               TREE_TYPE (arg) = error_mark_node;
5585               TREE_VALUE (argtype) = error_mark_node;
5586             }
5587 
5588           arg = DECL_CHAIN (arg);
5589           argtype = TREE_CHAIN (argtype);
5590         }
5591 
5592       /* Check for bare parameter packs in the return type and the
5593          exception specifiers.  */
5594       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5595 	/* Errors were already issued, set return type to int
5596 	   as the frontend doesn't expect error_mark_node as
5597 	   the return type.  */
5598 	TREE_TYPE (type) = integer_type_node;
5599       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5600 	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5601     }
5602   else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
5603 					    && TYPE_DECL_ALIAS_P (decl))
5604 					   ? DECL_ORIGINAL_TYPE (decl)
5605 					   : TREE_TYPE (decl)))
5606     {
5607       TREE_TYPE (decl) = error_mark_node;
5608       return error_mark_node;
5609     }
5610 
5611   if (is_partial)
5612     return process_partial_specialization (decl);
5613 
5614   args = current_template_args ();
5615 
5616   if (!ctx
5617       || TREE_CODE (ctx) == FUNCTION_DECL
5618       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5619       || (TREE_CODE (decl) == TYPE_DECL
5620 	  && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5621       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
5622     {
5623       if (DECL_LANG_SPECIFIC (decl)
5624 	  && DECL_TEMPLATE_INFO (decl)
5625 	  && DECL_TI_TEMPLATE (decl))
5626 	tmpl = DECL_TI_TEMPLATE (decl);
5627       /* If DECL is a TYPE_DECL for a class-template, then there won't
5628 	 be DECL_LANG_SPECIFIC.  The information equivalent to
5629 	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
5630       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5631 	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5632 	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5633 	{
5634 	  /* Since a template declaration already existed for this
5635 	     class-type, we must be redeclaring it here.  Make sure
5636 	     that the redeclaration is valid.  */
5637 	  redeclare_class_template (TREE_TYPE (decl),
5638 				    current_template_parms,
5639 				    current_template_constraints ());
5640 	  /* We don't need to create a new TEMPLATE_DECL; just use the
5641 	     one we already had.  */
5642 	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5643 	}
5644       else
5645 	{
5646 	  tmpl = build_template_decl (decl, current_template_parms,
5647 				      member_template_p);
5648 	  new_template_p = 1;
5649 
5650 	  if (DECL_LANG_SPECIFIC (decl)
5651 	      && DECL_TEMPLATE_SPECIALIZATION (decl))
5652 	    {
5653 	      /* A specialization of a member template of a template
5654 		 class.  */
5655 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5656 	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5657 	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5658 	    }
5659 	}
5660     }
5661   else
5662     {
5663       tree a, t, current, parms;
5664       int i;
5665       tree tinfo = get_template_info (decl);
5666 
5667       if (!tinfo)
5668 	{
5669 	  error ("template definition of non-template %q#D", decl);
5670 	  return error_mark_node;
5671 	}
5672 
5673       tmpl = TI_TEMPLATE (tinfo);
5674 
5675       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5676 	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5677 	  && DECL_TEMPLATE_SPECIALIZATION (decl)
5678 	  && DECL_MEMBER_TEMPLATE_P (tmpl))
5679 	{
5680 	  tree new_tmpl;
5681 
5682 	  /* The declaration is a specialization of a member
5683 	     template, declared outside the class.  Therefore, the
5684 	     innermost template arguments will be NULL, so we
5685 	     replace them with the arguments determined by the
5686 	     earlier call to check_explicit_specialization.  */
5687 	  args = DECL_TI_ARGS (decl);
5688 
5689 	  new_tmpl
5690 	    = build_template_decl (decl, current_template_parms,
5691 				   member_template_p);
5692 	  DECL_TEMPLATE_RESULT (new_tmpl) = decl;
5693 	  TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
5694 	  DECL_TI_TEMPLATE (decl) = new_tmpl;
5695 	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5696 	  DECL_TEMPLATE_INFO (new_tmpl)
5697 	    = build_template_info (tmpl, args);
5698 
5699 	  register_specialization (new_tmpl,
5700 				   most_general_template (tmpl),
5701 				   args,
5702 				   is_friend, 0);
5703 	  return decl;
5704 	}
5705 
5706       /* Make sure the template headers we got make sense.  */
5707 
5708       parms = DECL_TEMPLATE_PARMS (tmpl);
5709       i = TMPL_PARMS_DEPTH (parms);
5710       if (TMPL_ARGS_DEPTH (args) != i)
5711 	{
5712 	  error ("expected %d levels of template parms for %q#D, got %d",
5713 		 i, decl, TMPL_ARGS_DEPTH (args));
5714 	  DECL_INTERFACE_KNOWN (decl) = 1;
5715 	  return error_mark_node;
5716 	}
5717       else
5718 	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5719 	  {
5720 	    a = TMPL_ARGS_LEVEL (args, i);
5721 	    t = INNERMOST_TEMPLATE_PARMS (parms);
5722 
5723 	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5724 	      {
5725 		if (current == decl)
5726 		  error ("got %d template parameters for %q#D",
5727 			 TREE_VEC_LENGTH (a), decl);
5728 		else
5729 		  error ("got %d template parameters for %q#T",
5730 			 TREE_VEC_LENGTH (a), current);
5731 		error ("  but %d required", TREE_VEC_LENGTH (t));
5732 		/* Avoid crash in import_export_decl.  */
5733 		DECL_INTERFACE_KNOWN (decl) = 1;
5734 		return error_mark_node;
5735 	      }
5736 
5737 	    if (current == decl)
5738 	      current = ctx;
5739 	    else if (current == NULL_TREE)
5740 	      /* Can happen in erroneous input.  */
5741 	      break;
5742 	    else
5743 	      current = get_containing_scope (current);
5744 	  }
5745 
5746       /* Check that the parms are used in the appropriate qualifying scopes
5747 	 in the declarator.  */
5748       if (!comp_template_args
5749 	  (TI_ARGS (tinfo),
5750 	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5751 	{
5752 	  error ("template arguments to %qD do not match original "
5753 		 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
5754 	  if (!uses_template_parms (TI_ARGS (tinfo)))
5755 	    inform (input_location, "use %<template<>%> for"
5756 		    " an explicit specialization");
5757 	  /* Avoid crash in import_export_decl.  */
5758 	  DECL_INTERFACE_KNOWN (decl) = 1;
5759 	  return error_mark_node;
5760 	}
5761     }
5762 
5763   DECL_TEMPLATE_RESULT (tmpl) = decl;
5764   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5765 
5766   /* Push template declarations for global functions and types.  Note
5767      that we do not try to push a global template friend declared in a
5768      template class; such a thing may well depend on the template
5769      parameters of the class.  */
5770   if (new_template_p && !ctx
5771       && !(is_friend && template_class_depth (current_class_type) > 0))
5772     {
5773       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5774       if (tmpl == error_mark_node)
5775 	return error_mark_node;
5776 
5777       /* Hide template friend classes that haven't been declared yet.  */
5778       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5779 	{
5780 	  DECL_ANTICIPATED (tmpl) = 1;
5781 	  DECL_FRIEND_P (tmpl) = 1;
5782 	}
5783     }
5784 
5785   if (is_primary)
5786     {
5787       tree parms = DECL_TEMPLATE_PARMS (tmpl);
5788 
5789       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5790 
5791       /* Give template template parms a DECL_CONTEXT of the template
5792 	 for which they are a parameter.  */
5793       parms = INNERMOST_TEMPLATE_PARMS (parms);
5794       for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5795 	{
5796 	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5797 	  if (TREE_CODE (parm) == TEMPLATE_DECL)
5798 	    DECL_CONTEXT (parm) = tmpl;
5799 	}
5800 
5801       if (TREE_CODE (decl) == TYPE_DECL
5802 	  && TYPE_DECL_ALIAS_P (decl)
5803 	  && complex_alias_template_p (tmpl))
5804 	TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
5805     }
5806 
5807   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5808      back to its most general template.  If TMPL is a specialization,
5809      ARGS may only have the innermost set of arguments.  Add the missing
5810      argument levels if necessary.  */
5811   if (DECL_TEMPLATE_INFO (tmpl))
5812     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5813 
5814   info = build_template_info (tmpl, args);
5815 
5816   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5817     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5818   else
5819     {
5820       if (is_primary)
5821 	retrofit_lang_decl (decl);
5822       if (DECL_LANG_SPECIFIC (decl))
5823 	DECL_TEMPLATE_INFO (decl) = info;
5824     }
5825 
5826   if (flag_implicit_templates
5827       && !is_friend
5828       && TREE_PUBLIC (decl)
5829       && VAR_OR_FUNCTION_DECL_P (decl))
5830     /* Set DECL_COMDAT on template instantiations; if we force
5831        them to be emitted by explicit instantiation or -frepo,
5832        mark_needed will tell cgraph to do the right thing.  */
5833     DECL_COMDAT (decl) = true;
5834 
5835   return DECL_TEMPLATE_RESULT (tmpl);
5836 }
5837 
5838 tree
5839 push_template_decl (tree decl)
5840 {
5841   return push_template_decl_real (decl, false);
5842 }
5843 
5844 /* FN is an inheriting constructor that inherits from the constructor
5845    template INHERITED; turn FN into a constructor template with a matching
5846    template header.  */
5847 
5848 tree
5849 add_inherited_template_parms (tree fn, tree inherited)
5850 {
5851   tree inner_parms
5852     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
5853   inner_parms = copy_node (inner_parms);
5854   tree parms
5855     = tree_cons (size_int (processing_template_decl + 1),
5856 		 inner_parms, current_template_parms);
5857   tree tmpl = build_template_decl (fn, parms, /*member*/true);
5858   tree args = template_parms_to_args (parms);
5859   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
5860   TREE_TYPE (tmpl) = TREE_TYPE (fn);
5861   DECL_TEMPLATE_RESULT (tmpl) = fn;
5862   DECL_ARTIFICIAL (tmpl) = true;
5863   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5864   return tmpl;
5865 }
5866 
5867 /* Called when a class template TYPE is redeclared with the indicated
5868    template PARMS, e.g.:
5869 
5870      template <class T> struct S;
5871      template <class T> struct S {};  */
5872 
5873 bool
5874 redeclare_class_template (tree type, tree parms, tree cons)
5875 {
5876   tree tmpl;
5877   tree tmpl_parms;
5878   int i;
5879 
5880   if (!TYPE_TEMPLATE_INFO (type))
5881     {
5882       error ("%qT is not a template type", type);
5883       return false;
5884     }
5885 
5886   tmpl = TYPE_TI_TEMPLATE (type);
5887   if (!PRIMARY_TEMPLATE_P (tmpl))
5888     /* The type is nested in some template class.  Nothing to worry
5889        about here; there are no new template parameters for the nested
5890        type.  */
5891     return true;
5892 
5893   if (!parms)
5894     {
5895       error ("template specifiers not specified in declaration of %qD",
5896 	     tmpl);
5897       return false;
5898     }
5899 
5900   parms = INNERMOST_TEMPLATE_PARMS (parms);
5901   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5902 
5903   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5904     {
5905       error_n (input_location, TREE_VEC_LENGTH (parms),
5906                "redeclared with %d template parameter",
5907                "redeclared with %d template parameters",
5908                TREE_VEC_LENGTH (parms));
5909       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
5910                 "previous declaration %qD used %d template parameter",
5911                 "previous declaration %qD used %d template parameters",
5912                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5913       return false;
5914     }
5915 
5916   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5917     {
5918       tree tmpl_parm;
5919       tree parm;
5920       tree tmpl_default;
5921       tree parm_default;
5922 
5923       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5924           || TREE_VEC_ELT (parms, i) == error_mark_node)
5925         continue;
5926 
5927       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5928       if (error_operand_p (tmpl_parm))
5929 	return false;
5930 
5931       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5932       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5933       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5934 
5935       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5936 	 TEMPLATE_DECL.  */
5937       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5938 	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
5939 	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5940 	  || (TREE_CODE (tmpl_parm) != PARM_DECL
5941 	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5942 		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5943 	  || (TREE_CODE (tmpl_parm) == PARM_DECL
5944 	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5945 		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5946 	{
5947 	  error ("template parameter %q+#D", tmpl_parm);
5948 	  error ("redeclared here as %q#D", parm);
5949 	  return false;
5950 	}
5951 
5952       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5953 	{
5954 	  /* We have in [temp.param]:
5955 
5956 	     A template-parameter may not be given default arguments
5957 	     by two different declarations in the same scope.  */
5958 	  error_at (input_location, "redefinition of default argument for %q#D", parm);
5959 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
5960 		  "original definition appeared here");
5961 	  return false;
5962 	}
5963 
5964       if (parm_default != NULL_TREE)
5965 	/* Update the previous template parameters (which are the ones
5966 	   that will really count) with the new default value.  */
5967 	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5968       else if (tmpl_default != NULL_TREE)
5969 	/* Update the new parameters, too; they'll be used as the
5970 	   parameters for any members.  */
5971 	TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5972 
5973       /* Give each template template parm in this redeclaration a
5974 	 DECL_CONTEXT of the template for which they are a parameter.  */
5975       if (TREE_CODE (parm) == TEMPLATE_DECL)
5976 	{
5977 	  gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
5978 	  DECL_CONTEXT (parm) = tmpl;
5979 	}
5980 
5981       if (TREE_CODE (parm) == TYPE_DECL)
5982 	TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (parm)) = true;
5983     }
5984 
5985   // Cannot redeclare a class template with a different set of constraints.
5986   if (!equivalent_constraints (get_constraints (tmpl), cons))
5987     {
5988       error_at (input_location, "redeclaration %q#D with different "
5989                                 "constraints", tmpl);
5990       inform (DECL_SOURCE_LOCATION (tmpl),
5991               "original declaration appeared here");
5992     }
5993 
5994     return true;
5995 }
5996 
5997 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
5998    to be used when the caller has already checked
5999    (processing_template_decl
6000     && !instantiation_dependent_expression_p (expr)
6001     && potential_constant_expression (expr))
6002    and cleared processing_template_decl.  */
6003 
6004 tree
6005 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6006 {
6007   return tsubst_copy_and_build (expr,
6008 				/*args=*/NULL_TREE,
6009 				complain,
6010 				/*in_decl=*/NULL_TREE,
6011 				/*function_p=*/false,
6012 				/*integral_constant_expression_p=*/true);
6013 }
6014 
6015 /* Simplify EXPR if it is a non-dependent expression.  Returns the
6016    (possibly simplified) expression.  */
6017 
6018 tree
6019 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6020 {
6021   if (expr == NULL_TREE)
6022     return NULL_TREE;
6023 
6024   /* If we're in a template, but EXPR isn't value dependent, simplify
6025      it.  We're supposed to treat:
6026 
6027        template <typename T> void f(T[1 + 1]);
6028        template <typename T> void f(T[2]);
6029 
6030      as two declarations of the same function, for example.  */
6031   if (processing_template_decl
6032       && is_nondependent_constant_expression (expr))
6033     {
6034       processing_template_decl_sentinel s;
6035       expr = instantiate_non_dependent_expr_internal (expr, complain);
6036     }
6037   return expr;
6038 }
6039 
6040 tree
6041 instantiate_non_dependent_expr (tree expr)
6042 {
6043   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6044 }
6045 
6046 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
6047    an uninstantiated expression.  */
6048 
6049 tree
6050 instantiate_non_dependent_or_null (tree expr)
6051 {
6052   if (expr == NULL_TREE)
6053     return NULL_TREE;
6054   if (processing_template_decl)
6055     {
6056       if (!is_nondependent_constant_expression (expr))
6057 	expr = NULL_TREE;
6058       else
6059 	{
6060 	  processing_template_decl_sentinel s;
6061 	  expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6062 	}
6063     }
6064   return expr;
6065 }
6066 
6067 /* True iff T is a specialization of a variable template.  */
6068 
6069 bool
6070 variable_template_specialization_p (tree t)
6071 {
6072   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6073     return false;
6074   tree tmpl = DECL_TI_TEMPLATE (t);
6075   return variable_template_p (tmpl);
6076 }
6077 
6078 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6079    template declaration, or a TYPE_DECL for an alias declaration.  */
6080 
6081 bool
6082 alias_type_or_template_p (tree t)
6083 {
6084   if (t == NULL_TREE)
6085     return false;
6086   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6087 	  || (TYPE_P (t)
6088 	      && TYPE_NAME (t)
6089 	      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6090 	  || DECL_ALIAS_TEMPLATE_P (t));
6091 }
6092 
6093 /* Return TRUE iff T is a specialization of an alias template.  */
6094 
6095 bool
6096 alias_template_specialization_p (const_tree t)
6097 {
6098   /* It's an alias template specialization if it's an alias and its
6099      TYPE_NAME is a specialization of a primary template.  */
6100   if (TYPE_ALIAS_P (t))
6101     if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6102       return PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo));
6103 
6104   return false;
6105 }
6106 
6107 /* An alias template is complex from a SFINAE perspective if a template-id
6108    using that alias can be ill-formed when the expansion is not, as with
6109    the void_t template.  We determine this by checking whether the
6110    expansion for the alias template uses all its template parameters.  */
6111 
6112 struct uses_all_template_parms_data
6113 {
6114   int level;
6115   bool *seen;
6116 };
6117 
6118 static int
6119 uses_all_template_parms_r (tree t, void *data_)
6120 {
6121   struct uses_all_template_parms_data &data
6122     = *(struct uses_all_template_parms_data*)data_;
6123   tree idx = get_template_parm_index (t);
6124 
6125   if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6126     data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6127   return 0;
6128 }
6129 
6130 static bool
6131 complex_alias_template_p (const_tree tmpl)
6132 {
6133   struct uses_all_template_parms_data data;
6134   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6135   tree parms = DECL_TEMPLATE_PARMS (tmpl);
6136   data.level = TMPL_PARMS_DEPTH (parms);
6137   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6138   data.seen = XALLOCAVEC (bool, len);
6139   for (int i = 0; i < len; ++i)
6140     data.seen[i] = false;
6141 
6142   for_each_template_parm (pat, uses_all_template_parms_r, &data, NULL, true);
6143   for (int i = 0; i < len; ++i)
6144     if (!data.seen[i])
6145       return true;
6146   return false;
6147 }
6148 
6149 /* Return TRUE iff T is a specialization of a complex alias template with
6150    dependent template-arguments.  */
6151 
6152 bool
6153 dependent_alias_template_spec_p (const_tree t)
6154 {
6155   if (!alias_template_specialization_p (t))
6156     return false;
6157 
6158   tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6159   if (!TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo)))
6160     return false;
6161 
6162   tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
6163   if (!any_dependent_template_arguments_p (args))
6164     return false;
6165 
6166   return true;
6167 }
6168 
6169 /* Return the number of innermost template parameters in TMPL.  */
6170 
6171 static int
6172 num_innermost_template_parms (tree tmpl)
6173 {
6174   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6175   return TREE_VEC_LENGTH (parms);
6176 }
6177 
6178 /* Return either TMPL or another template that it is equivalent to under DR
6179    1286: An alias that just changes the name of a template is equivalent to
6180    the other template.  */
6181 
6182 static tree
6183 get_underlying_template (tree tmpl)
6184 {
6185   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6186   while (DECL_ALIAS_TEMPLATE_P (tmpl))
6187     {
6188       /* Determine if the alias is equivalent to an underlying template.  */
6189       tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6190       tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6191       if (!tinfo)
6192 	break;
6193 
6194       tree underlying = TI_TEMPLATE (tinfo);
6195       if (!PRIMARY_TEMPLATE_P (underlying)
6196 	  || (num_innermost_template_parms (tmpl)
6197 	      != num_innermost_template_parms (underlying)))
6198 	break;
6199 
6200       tree alias_args = INNERMOST_TEMPLATE_ARGS
6201 	(template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl)));
6202       if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6203 	break;
6204 
6205       /* Alias is equivalent.  Strip it and repeat.  */
6206       tmpl = underlying;
6207     }
6208 
6209   return tmpl;
6210 }
6211 
6212 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6213    must be a reference-to-function or a pointer-to-function type, as specified
6214    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6215    and check that the resulting function has external linkage.  */
6216 
6217 static tree
6218 convert_nontype_argument_function (tree type, tree expr,
6219 				   tsubst_flags_t complain)
6220 {
6221   tree fns = expr;
6222   tree fn, fn_no_ptr;
6223   linkage_kind linkage;
6224 
6225   fn = instantiate_type (type, fns, tf_none);
6226   if (fn == error_mark_node)
6227     return error_mark_node;
6228 
6229   if (value_dependent_expression_p (fn))
6230     goto accept;
6231 
6232   fn_no_ptr = strip_fnptr_conv (fn);
6233   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6234     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6235   if (BASELINK_P (fn_no_ptr))
6236     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6237 
6238   /* [temp.arg.nontype]/1
6239 
6240      A template-argument for a non-type, non-template template-parameter
6241      shall be one of:
6242      [...]
6243      -- the address of an object or function with external [C++11: or
6244         internal] linkage.  */
6245 
6246   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6247     {
6248       if (complain & tf_error)
6249 	{
6250 	  error ("%qE is not a valid template argument for type %qT",
6251 		 expr, type);
6252 	  if (TYPE_PTR_P (type))
6253 	    inform (input_location, "it must be the address of a function "
6254 		    "with external linkage");
6255 	  else
6256 	    inform (input_location, "it must be the name of a function with "
6257 		    "external linkage");
6258 	}
6259       return NULL_TREE;
6260     }
6261 
6262   linkage = decl_linkage (fn_no_ptr);
6263   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6264     {
6265       if (complain & tf_error)
6266 	{
6267 	  if (cxx_dialect >= cxx11)
6268 	    error ("%qE is not a valid template argument for type %qT "
6269 		   "because %qD has no linkage",
6270 		   expr, type, fn_no_ptr);
6271 	  else
6272 	    error ("%qE is not a valid template argument for type %qT "
6273 		   "because %qD does not have external linkage",
6274 		   expr, type, fn_no_ptr);
6275 	}
6276       return NULL_TREE;
6277     }
6278 
6279  accept:
6280   if (TREE_CODE (type) == REFERENCE_TYPE)
6281     {
6282       if (REFERENCE_REF_P (fn))
6283 	fn = TREE_OPERAND (fn, 0);
6284       else
6285 	fn = build_address (fn);
6286     }
6287   if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6288     fn = build_nop (type, fn);
6289 
6290   return fn;
6291 }
6292 
6293 /* Subroutine of convert_nontype_argument.
6294    Check if EXPR of type TYPE is a valid pointer-to-member constant.
6295    Emit an error otherwise.  */
6296 
6297 static bool
6298 check_valid_ptrmem_cst_expr (tree type, tree expr,
6299 			     tsubst_flags_t complain)
6300 {
6301   location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
6302   tree orig_expr = expr;
6303   STRIP_NOPS (expr);
6304   if (null_ptr_cst_p (expr))
6305     return true;
6306   if (TREE_CODE (expr) == PTRMEM_CST
6307       && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6308 		      PTRMEM_CST_CLASS (expr)))
6309     return true;
6310   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6311     return true;
6312   if (processing_template_decl
6313       && TREE_CODE (expr) == ADDR_EXPR
6314       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6315     return true;
6316   if (complain & tf_error)
6317     {
6318       error_at (loc, "%qE is not a valid template argument for type %qT",
6319 		orig_expr, type);
6320       if (TREE_CODE (expr) != PTRMEM_CST)
6321 	inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6322       else
6323 	inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6324     }
6325   return false;
6326 }
6327 
6328 /* Returns TRUE iff the address of OP is value-dependent.
6329 
6330    14.6.2.4 [temp.dep.temp]:
6331    A non-integral non-type template-argument is dependent if its type is
6332    dependent or it has either of the following forms
6333      qualified-id
6334      & qualified-id
6335    and contains a nested-name-specifier which specifies a class-name that
6336    names a dependent type.
6337 
6338    We generalize this to just say that the address of a member of a
6339    dependent class is value-dependent; the above doesn't cover the
6340    address of a static data member named with an unqualified-id.  */
6341 
6342 static bool
6343 has_value_dependent_address (tree op)
6344 {
6345   /* We could use get_inner_reference here, but there's no need;
6346      this is only relevant for template non-type arguments, which
6347      can only be expressed as &id-expression.  */
6348   if (DECL_P (op))
6349     {
6350       tree ctx = CP_DECL_CONTEXT (op);
6351       if (TYPE_P (ctx) && dependent_type_p (ctx))
6352 	return true;
6353     }
6354 
6355   return false;
6356 }
6357 
6358 /* The next set of functions are used for providing helpful explanatory
6359    diagnostics for failed overload resolution.  Their messages should be
6360    indented by two spaces for consistency with the messages in
6361    call.c  */
6362 
6363 static int
6364 unify_success (bool /*explain_p*/)
6365 {
6366   return 0;
6367 }
6368 
6369 /* Other failure functions should call this one, to provide a single function
6370    for setting a breakpoint on.  */
6371 
6372 static int
6373 unify_invalid (bool /*explain_p*/)
6374 {
6375   return 1;
6376 }
6377 
6378 static int
6379 unify_parameter_deduction_failure (bool explain_p, tree parm)
6380 {
6381   if (explain_p)
6382     inform (input_location,
6383 	    "  couldn't deduce template parameter %qD", parm);
6384   return unify_invalid (explain_p);
6385 }
6386 
6387 static int
6388 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6389 {
6390   if (explain_p)
6391     inform (input_location,
6392 	    "  types %qT and %qT have incompatible cv-qualifiers",
6393 	    parm, arg);
6394   return unify_invalid (explain_p);
6395 }
6396 
6397 static int
6398 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6399 {
6400   if (explain_p)
6401     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6402   return unify_invalid (explain_p);
6403 }
6404 
6405 static int
6406 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6407 {
6408   if (explain_p)
6409     inform (input_location,
6410 	    "  template parameter %qD is not a parameter pack, but "
6411 	    "argument %qD is",
6412 	    parm, arg);
6413   return unify_invalid (explain_p);
6414 }
6415 
6416 static int
6417 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6418 {
6419   if (explain_p)
6420     inform (input_location,
6421 	    "  template argument %qE does not match "
6422 	    "pointer-to-member constant %qE",
6423 	    arg, parm);
6424   return unify_invalid (explain_p);
6425 }
6426 
6427 static int
6428 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6429 {
6430   if (explain_p)
6431     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6432   return unify_invalid (explain_p);
6433 }
6434 
6435 static int
6436 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6437 {
6438   if (explain_p)
6439     inform (input_location,
6440 	    "  inconsistent parameter pack deduction with %qT and %qT",
6441 	    old_arg, new_arg);
6442   return unify_invalid (explain_p);
6443 }
6444 
6445 static int
6446 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6447 {
6448   if (explain_p)
6449     {
6450       if (TYPE_P (parm))
6451 	inform (input_location,
6452 		"  deduced conflicting types for parameter %qT (%qT and %qT)",
6453 		parm, first, second);
6454       else
6455 	inform (input_location,
6456 		"  deduced conflicting values for non-type parameter "
6457 		"%qE (%qE and %qE)", parm, first, second);
6458     }
6459   return unify_invalid (explain_p);
6460 }
6461 
6462 static int
6463 unify_vla_arg (bool explain_p, tree arg)
6464 {
6465   if (explain_p)
6466     inform (input_location,
6467 	    "  variable-sized array type %qT is not "
6468 	    "a valid template argument",
6469 	    arg);
6470   return unify_invalid (explain_p);
6471 }
6472 
6473 static int
6474 unify_method_type_error (bool explain_p, tree arg)
6475 {
6476   if (explain_p)
6477     inform (input_location,
6478 	    "  member function type %qT is not a valid template argument",
6479 	    arg);
6480   return unify_invalid (explain_p);
6481 }
6482 
6483 static int
6484 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6485 {
6486   if (explain_p)
6487     {
6488       if (least_p)
6489 	inform_n (input_location, wanted,
6490 		  "  candidate expects at least %d argument, %d provided",
6491 		  "  candidate expects at least %d arguments, %d provided",
6492 		  wanted, have);
6493       else
6494 	inform_n (input_location, wanted,
6495 		  "  candidate expects %d argument, %d provided",
6496 		  "  candidate expects %d arguments, %d provided",
6497 		  wanted, have);
6498     }
6499   return unify_invalid (explain_p);
6500 }
6501 
6502 static int
6503 unify_too_many_arguments (bool explain_p, int have, int wanted)
6504 {
6505   return unify_arity (explain_p, have, wanted);
6506 }
6507 
6508 static int
6509 unify_too_few_arguments (bool explain_p, int have, int wanted,
6510 			 bool least_p = false)
6511 {
6512   return unify_arity (explain_p, have, wanted, least_p);
6513 }
6514 
6515 static int
6516 unify_arg_conversion (bool explain_p, tree to_type,
6517 		      tree from_type, tree arg)
6518 {
6519   if (explain_p)
6520     inform (EXPR_LOC_OR_LOC (arg, input_location),
6521 	    "  cannot convert %qE (type %qT) to type %qT",
6522 	    arg, from_type, to_type);
6523   return unify_invalid (explain_p);
6524 }
6525 
6526 static int
6527 unify_no_common_base (bool explain_p, enum template_base_result r,
6528 		      tree parm, tree arg)
6529 {
6530   if (explain_p)
6531     switch (r)
6532       {
6533       case tbr_ambiguous_baseclass:
6534 	inform (input_location, "  %qT is an ambiguous base class of %qT",
6535 		parm, arg);
6536 	break;
6537       default:
6538 	inform (input_location, "  %qT is not derived from %qT", arg, parm);
6539 	break;
6540       }
6541   return unify_invalid (explain_p);
6542 }
6543 
6544 static int
6545 unify_inconsistent_template_template_parameters (bool explain_p)
6546 {
6547   if (explain_p)
6548     inform (input_location,
6549 	    "  template parameters of a template template argument are "
6550 	    "inconsistent with other deduced template arguments");
6551   return unify_invalid (explain_p);
6552 }
6553 
6554 static int
6555 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6556 {
6557   if (explain_p)
6558     inform (input_location,
6559 	    "  can't deduce a template for %qT from non-template type %qT",
6560 	    parm, arg);
6561   return unify_invalid (explain_p);
6562 }
6563 
6564 static int
6565 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6566 {
6567   if (explain_p)
6568     inform (input_location,
6569 	    "  template argument %qE does not match %qE", arg, parm);
6570   return unify_invalid (explain_p);
6571 }
6572 
6573 /* Attempt to convert the non-type template parameter EXPR to the
6574    indicated TYPE.  If the conversion is successful, return the
6575    converted value.  If the conversion is unsuccessful, return
6576    NULL_TREE if we issued an error message, or error_mark_node if we
6577    did not.  We issue error messages for out-and-out bad template
6578    parameters, but not simply because the conversion failed, since we
6579    might be just trying to do argument deduction.  Both TYPE and EXPR
6580    must be non-dependent.
6581 
6582    The conversion follows the special rules described in
6583    [temp.arg.nontype], and it is much more strict than an implicit
6584    conversion.
6585 
6586    This function is called twice for each template argument (see
6587    lookup_template_class for a more accurate description of this
6588    problem). This means that we need to handle expressions which
6589    are not valid in a C++ source, but can be created from the
6590    first call (for instance, casts to perform conversions). These
6591    hacks can go away after we fix the double coercion problem.  */
6592 
6593 static tree
6594 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
6595 {
6596   tree expr_type;
6597   location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
6598   tree orig_expr = expr;
6599 
6600   /* Detect immediately string literals as invalid non-type argument.
6601      This special-case is not needed for correctness (we would easily
6602      catch this later), but only to provide better diagnostic for this
6603      common user mistake. As suggested by DR 100, we do not mention
6604      linkage issues in the diagnostic as this is not the point.  */
6605   /* FIXME we're making this OK.  */
6606   if (TREE_CODE (expr) == STRING_CST)
6607     {
6608       if (complain & tf_error)
6609 	error ("%qE is not a valid template argument for type %qT "
6610 	       "because string literals can never be used in this context",
6611 	       expr, type);
6612       return NULL_TREE;
6613     }
6614 
6615   /* Add the ADDR_EXPR now for the benefit of
6616      value_dependent_expression_p.  */
6617   if (TYPE_PTROBV_P (type)
6618       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
6619     {
6620       expr = decay_conversion (expr, complain);
6621       if (expr == error_mark_node)
6622 	return error_mark_node;
6623     }
6624 
6625   /* If we are in a template, EXPR may be non-dependent, but still
6626      have a syntactic, rather than semantic, form.  For example, EXPR
6627      might be a SCOPE_REF, rather than the VAR_DECL to which the
6628      SCOPE_REF refers.  Preserving the qualifying scope is necessary
6629      so that access checking can be performed when the template is
6630      instantiated -- but here we need the resolved form so that we can
6631      convert the argument.  */
6632   bool non_dep = false;
6633   if (TYPE_REF_OBJ_P (type)
6634       && has_value_dependent_address (expr))
6635     /* If we want the address and it's value-dependent, don't fold.  */;
6636   else if (processing_template_decl
6637 	   && is_nondependent_constant_expression (expr))
6638     non_dep = true;
6639   if (error_operand_p (expr))
6640     return error_mark_node;
6641   expr_type = TREE_TYPE (expr);
6642 
6643   /* If the argument is non-dependent, perform any conversions in
6644      non-dependent context as well.  */
6645   processing_template_decl_sentinel s (non_dep);
6646   if (non_dep)
6647     expr = instantiate_non_dependent_expr_internal (expr, complain);
6648 
6649   if (value_dependent_expression_p (expr))
6650     expr = canonicalize_expr_argument (expr, complain);
6651 
6652   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
6653      to a non-type argument of "nullptr".  */
6654   if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
6655     expr = fold_simple (convert (type, expr));
6656 
6657   /* In C++11, integral or enumeration non-type template arguments can be
6658      arbitrary constant expressions.  Pointer and pointer to
6659      member arguments can be general constant expressions that evaluate
6660      to a null value, but otherwise still need to be of a specific form.  */
6661   if (cxx_dialect >= cxx11)
6662     {
6663       if (TREE_CODE (expr) == PTRMEM_CST)
6664 	/* A PTRMEM_CST is already constant, and a valid template
6665 	   argument for a parameter of pointer to member type, we just want
6666 	   to leave it in that form rather than lower it to a
6667 	   CONSTRUCTOR.  */;
6668       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
6669 	       || cxx_dialect >= cxx17)
6670 	{
6671 	  /* C++17: A template-argument for a non-type template-parameter shall
6672 	     be a converted constant expression (8.20) of the type of the
6673 	     template-parameter.  */
6674 	  expr = build_converted_constant_expr (type, expr, complain);
6675 	  if (expr == error_mark_node)
6676 	    return error_mark_node;
6677 	  expr = maybe_constant_value (expr);
6678 	  expr = convert_from_reference (expr);
6679 	}
6680       else if (TYPE_PTR_OR_PTRMEM_P (type))
6681 	{
6682 	  tree folded = maybe_constant_value (expr);
6683 	  if (TYPE_PTR_P (type) ? integer_zerop (folded)
6684 	      : null_member_pointer_value_p (folded))
6685 	    expr = folded;
6686 	}
6687     }
6688 
6689   if (TREE_CODE (type) == REFERENCE_TYPE)
6690     expr = mark_lvalue_use (expr);
6691   else
6692     expr = mark_rvalue_use (expr);
6693 
6694   /* HACK: Due to double coercion, we can get a
6695      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
6696      which is the tree that we built on the first call (see
6697      below when coercing to reference to object or to reference to
6698      function). We just strip everything and get to the arg.
6699      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
6700      for examples.  */
6701   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
6702     {
6703       tree probe_type, probe = expr;
6704       if (REFERENCE_REF_P (probe))
6705 	probe = TREE_OPERAND (probe, 0);
6706       probe_type = TREE_TYPE (probe);
6707       if (TREE_CODE (probe) == NOP_EXPR)
6708 	{
6709 	  /* ??? Maybe we could use convert_from_reference here, but we
6710 	     would need to relax its constraints because the NOP_EXPR
6711 	     could actually change the type to something more cv-qualified,
6712 	     and this is not folded by convert_from_reference.  */
6713 	  tree addr = TREE_OPERAND (probe, 0);
6714 	  if (TREE_CODE (probe_type) == REFERENCE_TYPE
6715 	      && TREE_CODE (addr) == ADDR_EXPR
6716 	      && TYPE_PTR_P (TREE_TYPE (addr))
6717 	      && (same_type_ignoring_top_level_qualifiers_p
6718 		  (TREE_TYPE (probe_type),
6719 		   TREE_TYPE (TREE_TYPE (addr)))))
6720 	    {
6721 	      expr = TREE_OPERAND (addr, 0);
6722 	      expr_type = TREE_TYPE (probe_type);
6723 	    }
6724 	}
6725     }
6726 
6727   /* [temp.arg.nontype]/5, bullet 1
6728 
6729      For a non-type template-parameter of integral or enumeration type,
6730      integral promotions (_conv.prom_) and integral conversions
6731      (_conv.integral_) are applied.  */
6732   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6733     {
6734       if (cxx_dialect < cxx11)
6735 	{
6736 	  tree t = build_converted_constant_expr (type, expr, complain);
6737 	  t = maybe_constant_value (t);
6738 	  if (t != error_mark_node)
6739 	    expr = t;
6740 	}
6741 
6742       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
6743 	return error_mark_node;
6744 
6745       /* Notice that there are constant expressions like '4 % 0' which
6746 	 do not fold into integer constants.  */
6747       if (TREE_CODE (expr) != INTEGER_CST
6748 	  && !value_dependent_expression_p (expr))
6749 	{
6750 	  if (complain & tf_error)
6751 	    {
6752 	      int errs = errorcount, warns = warningcount + werrorcount;
6753 	      if (!require_potential_constant_expression (expr))
6754 		expr = error_mark_node;
6755 	      else
6756 		expr = cxx_constant_value (expr);
6757 	      if (errorcount > errs || warningcount + werrorcount > warns)
6758 		inform (loc, "in template argument for type %qT", type);
6759 	      if (expr == error_mark_node)
6760 		return NULL_TREE;
6761 	      /* else cxx_constant_value complained but gave us
6762 		 a real constant, so go ahead.  */
6763 	      if (TREE_CODE (expr) != INTEGER_CST)
6764 		{
6765 		  /* Some assemble time constant expressions like
6766 		     (intptr_t)&&lab1 - (intptr_t)&&lab2 or
6767 		     4 + (intptr_t)&&var satisfy reduced_constant_expression_p
6768 		     as we can emit them into .rodata initializers of
6769 		     variables, yet they can't fold into an INTEGER_CST at
6770 		     compile time.  Refuse them here.  */
6771 		  gcc_checking_assert (reduced_constant_expression_p (expr));
6772 		  error_at (loc, "template argument %qE for type %qT not "
6773 				 "a constant integer", expr, type);
6774 		  return NULL_TREE;
6775 		}
6776 	    }
6777 	  else
6778 	    return NULL_TREE;
6779 	}
6780 
6781       /* Avoid typedef problems.  */
6782       if (TREE_TYPE (expr) != type)
6783 	expr = fold_convert (type, expr);
6784     }
6785   /* [temp.arg.nontype]/5, bullet 2
6786 
6787      For a non-type template-parameter of type pointer to object,
6788      qualification conversions (_conv.qual_) and the array-to-pointer
6789      conversion (_conv.array_) are applied.  */
6790   else if (TYPE_PTROBV_P (type))
6791     {
6792       tree decayed = expr;
6793 
6794       /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
6795 	 decay_conversion or an explicit cast.  If it's a problematic cast,
6796 	 we'll complain about it below.  */
6797       if (TREE_CODE (expr) == NOP_EXPR)
6798 	{
6799 	  tree probe = expr;
6800 	  STRIP_NOPS (probe);
6801 	  if (TREE_CODE (probe) == ADDR_EXPR
6802 	      && TYPE_PTR_P (TREE_TYPE (probe)))
6803 	    {
6804 	      expr = probe;
6805 	      expr_type = TREE_TYPE (expr);
6806 	    }
6807 	}
6808 
6809       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
6810 
6811 	 A template-argument for a non-type, non-template template-parameter
6812 	 shall be one of: [...]
6813 
6814 	 -- the name of a non-type template-parameter;
6815 	 -- the address of an object or function with external linkage, [...]
6816 	    expressed as "& id-expression" where the & is optional if the name
6817 	    refers to a function or array, or if the corresponding
6818 	    template-parameter is a reference.
6819 
6820 	Here, we do not care about functions, as they are invalid anyway
6821 	for a parameter of type pointer-to-object.  */
6822 
6823       if (value_dependent_expression_p (expr))
6824 	/* Non-type template parameters are OK.  */
6825 	;
6826       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
6827 	/* Null pointer values are OK in C++11.  */;
6828       else if (TREE_CODE (expr) != ADDR_EXPR)
6829 	{
6830 	  if (VAR_P (expr))
6831 	    {
6832 	      if (complain & tf_error)
6833 		error ("%qD is not a valid template argument "
6834 		       "because %qD is a variable, not the address of "
6835 		       "a variable", orig_expr, expr);
6836 	      return NULL_TREE;
6837 	    }
6838 	  if (POINTER_TYPE_P (expr_type))
6839 	    {
6840 	      if (complain & tf_error)
6841 		error ("%qE is not a valid template argument for %qT "
6842 		       "because it is not the address of a variable",
6843 		       orig_expr, type);
6844 	      return NULL_TREE;
6845 	    }
6846 	  /* Other values, like integer constants, might be valid
6847 	     non-type arguments of some other type.  */
6848 	  return error_mark_node;
6849 	}
6850       else
6851 	{
6852 	  tree decl = TREE_OPERAND (expr, 0);
6853 
6854 	  if (!VAR_P (decl))
6855 	    {
6856 	      if (complain & tf_error)
6857 		error ("%qE is not a valid template argument of type %qT "
6858 		       "because %qE is not a variable", orig_expr, type, decl);
6859 	      return NULL_TREE;
6860 	    }
6861 	  else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6862 	    {
6863 	      if (complain & tf_error)
6864 		error ("%qE is not a valid template argument of type %qT "
6865 		       "because %qD does not have external linkage",
6866 		       orig_expr, type, decl);
6867 	      return NULL_TREE;
6868 	    }
6869 	  else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
6870 		   && decl_linkage (decl) == lk_none)
6871 	    {
6872 	      if (complain & tf_error)
6873 		error ("%qE is not a valid template argument of type %qT "
6874 		       "because %qD has no linkage", orig_expr, type, decl);
6875 	      return NULL_TREE;
6876 	    }
6877 	  /* C++17: For a non-type template-parameter of reference or pointer
6878 	     type, the value of the constant expression shall not refer to (or
6879 	     for a pointer type, shall not be the address of):
6880 	       * a subobject (4.5),
6881 	       * a temporary object (15.2),
6882 	       * a string literal (5.13.5),
6883 	       * the result of a typeid expression (8.2.8), or
6884 	       * a predefined __func__ variable (11.4.1).  */
6885 	  else if (DECL_ARTIFICIAL (decl))
6886 	    {
6887 	      if (complain & tf_error)
6888 		error ("the address of %qD is not a valid template argument",
6889 		       decl);
6890 	      return NULL_TREE;
6891 	    }
6892 	  else if (!same_type_ignoring_top_level_qualifiers_p
6893 		   (strip_array_types (TREE_TYPE (type)),
6894 		    strip_array_types (TREE_TYPE (decl))))
6895 	    {
6896 	      if (complain & tf_error)
6897 		error ("the address of the %qT subobject of %qD is not a "
6898 		       "valid template argument", TREE_TYPE (type), decl);
6899 	      return NULL_TREE;
6900 	    }
6901 	  else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
6902 	    {
6903 	      if (complain & tf_error)
6904 		error ("the address of %qD is not a valid template argument "
6905 		       "because it does not have static storage duration",
6906 		       decl);
6907 	      return NULL_TREE;
6908 	    }
6909 	}
6910 
6911       expr = decayed;
6912 
6913       expr = perform_qualification_conversions (type, expr);
6914       if (expr == error_mark_node)
6915 	return error_mark_node;
6916     }
6917   /* [temp.arg.nontype]/5, bullet 3
6918 
6919      For a non-type template-parameter of type reference to object, no
6920      conversions apply. The type referred to by the reference may be more
6921      cv-qualified than the (otherwise identical) type of the
6922      template-argument. The template-parameter is bound directly to the
6923      template-argument, which must be an lvalue.  */
6924   else if (TYPE_REF_OBJ_P (type))
6925     {
6926       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
6927 						      expr_type))
6928 	return error_mark_node;
6929 
6930       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
6931 	{
6932 	  if (complain & tf_error)
6933 	    error ("%qE is not a valid template argument for type %qT "
6934 		   "because of conflicts in cv-qualification", expr, type);
6935 	  return NULL_TREE;
6936 	}
6937 
6938       if (!lvalue_p (expr))
6939 	{
6940 	  if (complain & tf_error)
6941 	    error ("%qE is not a valid template argument for type %qT "
6942 		   "because it is not an lvalue", expr, type);
6943 	  return NULL_TREE;
6944 	}
6945 
6946       /* [temp.arg.nontype]/1
6947 
6948 	 A template-argument for a non-type, non-template template-parameter
6949 	 shall be one of: [...]
6950 
6951 	 -- the address of an object or function with external linkage.  */
6952       if (INDIRECT_REF_P (expr)
6953 	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
6954 	{
6955 	  expr = TREE_OPERAND (expr, 0);
6956 	  if (DECL_P (expr))
6957 	    {
6958 	      if (complain & tf_error)
6959 		error ("%q#D is not a valid template argument for type %qT "
6960 		       "because a reference variable does not have a constant "
6961 		       "address", expr, type);
6962 	      return NULL_TREE;
6963 	    }
6964 	}
6965 
6966       if (TYPE_REF_OBJ_P (TREE_TYPE (expr))
6967 	  && value_dependent_expression_p (expr))
6968 	/* OK, dependent reference.  We don't want to ask whether a DECL is
6969 	   itself value-dependent, since what we want here is its address.  */;
6970       else
6971 	{
6972 	  if (!DECL_P (expr))
6973 	    {
6974 	      if (complain & tf_error)
6975 		error ("%qE is not a valid template argument for type %qT "
6976 		       "because it is not an object with linkage",
6977 		       expr, type);
6978 	      return NULL_TREE;
6979 	    }
6980 
6981 	  /* DR 1155 allows internal linkage in C++11 and up.  */
6982 	  linkage_kind linkage = decl_linkage (expr);
6983 	  if (linkage < (cxx_dialect >= cxx11 ? lk_internal : lk_external))
6984 	    {
6985 	      if (complain & tf_error)
6986 		error ("%qE is not a valid template argument for type %qT "
6987 		       "because object %qD does not have linkage",
6988 		       expr, type, expr);
6989 	      return NULL_TREE;
6990 	    }
6991 
6992 	  expr = build_address (expr);
6993 	}
6994 
6995       if (!same_type_p (type, TREE_TYPE (expr)))
6996 	expr = build_nop (type, expr);
6997     }
6998   /* [temp.arg.nontype]/5, bullet 4
6999 
7000      For a non-type template-parameter of type pointer to function, only
7001      the function-to-pointer conversion (_conv.func_) is applied. If the
7002      template-argument represents a set of overloaded functions (or a
7003      pointer to such), the matching function is selected from the set
7004      (_over.over_).  */
7005   else if (TYPE_PTRFN_P (type))
7006     {
7007       /* If the argument is a template-id, we might not have enough
7008 	 context information to decay the pointer.  */
7009       if (!type_unknown_p (expr_type))
7010 	{
7011 	  expr = decay_conversion (expr, complain);
7012 	  if (expr == error_mark_node)
7013 	    return error_mark_node;
7014 	}
7015 
7016       if (cxx_dialect >= cxx11 && integer_zerop (expr))
7017 	/* Null pointer values are OK in C++11.  */
7018 	return perform_qualification_conversions (type, expr);
7019 
7020       expr = convert_nontype_argument_function (type, expr, complain);
7021       if (!expr || expr == error_mark_node)
7022 	return expr;
7023     }
7024   /* [temp.arg.nontype]/5, bullet 5
7025 
7026      For a non-type template-parameter of type reference to function, no
7027      conversions apply. If the template-argument represents a set of
7028      overloaded functions, the matching function is selected from the set
7029      (_over.over_).  */
7030   else if (TYPE_REFFN_P (type))
7031     {
7032       if (TREE_CODE (expr) == ADDR_EXPR)
7033 	{
7034 	  if (complain & tf_error)
7035 	    {
7036 	      error ("%qE is not a valid template argument for type %qT "
7037 		     "because it is a pointer", expr, type);
7038 	      inform (input_location, "try using %qE instead",
7039 		      TREE_OPERAND (expr, 0));
7040 	    }
7041 	  return NULL_TREE;
7042 	}
7043 
7044       expr = convert_nontype_argument_function (type, expr, complain);
7045       if (!expr || expr == error_mark_node)
7046 	return expr;
7047     }
7048   /* [temp.arg.nontype]/5, bullet 6
7049 
7050      For a non-type template-parameter of type pointer to member function,
7051      no conversions apply. If the template-argument represents a set of
7052      overloaded member functions, the matching member function is selected
7053      from the set (_over.over_).  */
7054   else if (TYPE_PTRMEMFUNC_P (type))
7055     {
7056       expr = instantiate_type (type, expr, tf_none);
7057       if (expr == error_mark_node)
7058 	return error_mark_node;
7059 
7060       /* [temp.arg.nontype] bullet 1 says the pointer to member
7061          expression must be a pointer-to-member constant.  */
7062       if (!value_dependent_expression_p (expr)
7063 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7064 	return NULL_TREE;
7065 
7066       /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7067 	 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead.  */
7068       if (fnptr_conv_p (type, TREE_TYPE (expr)))
7069 	expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7070     }
7071   /* [temp.arg.nontype]/5, bullet 7
7072 
7073      For a non-type template-parameter of type pointer to data member,
7074      qualification conversions (_conv.qual_) are applied.  */
7075   else if (TYPE_PTRDATAMEM_P (type))
7076     {
7077       /* [temp.arg.nontype] bullet 1 says the pointer to member
7078          expression must be a pointer-to-member constant.  */
7079       if (!value_dependent_expression_p (expr)
7080 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7081 	return NULL_TREE;
7082 
7083       expr = perform_qualification_conversions (type, expr);
7084       if (expr == error_mark_node)
7085 	return expr;
7086     }
7087   else if (NULLPTR_TYPE_P (type))
7088     {
7089       if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7090 	{
7091 	  if (complain & tf_error)
7092 	    error ("%qE is not a valid template argument for type %qT "
7093 		   "because it is of type %qT", expr, type, TREE_TYPE (expr));
7094 	  return NULL_TREE;
7095 	}
7096       return expr;
7097     }
7098   /* A template non-type parameter must be one of the above.  */
7099   else
7100     gcc_unreachable ();
7101 
7102   /* Sanity check: did we actually convert the argument to the
7103      right type?  */
7104   gcc_assert (same_type_ignoring_top_level_qualifiers_p
7105 	      (type, TREE_TYPE (expr)));
7106   return convert_from_reference (expr);
7107 }
7108 
7109 /* Subroutine of coerce_template_template_parms, which returns 1 if
7110    PARM_PARM and ARG_PARM match using the rule for the template
7111    parameters of template template parameters. Both PARM and ARG are
7112    template parameters; the rest of the arguments are the same as for
7113    coerce_template_template_parms.
7114  */
7115 static int
7116 coerce_template_template_parm (tree parm,
7117                               tree arg,
7118                               tsubst_flags_t complain,
7119                               tree in_decl,
7120                               tree outer_args)
7121 {
7122   if (arg == NULL_TREE || error_operand_p (arg)
7123       || parm == NULL_TREE || error_operand_p (parm))
7124     return 0;
7125 
7126   if (TREE_CODE (arg) != TREE_CODE (parm))
7127     return 0;
7128 
7129   switch (TREE_CODE (parm))
7130     {
7131     case TEMPLATE_DECL:
7132       /* We encounter instantiations of templates like
7133 	 template <template <template <class> class> class TT>
7134 	 class C;  */
7135       {
7136 	tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7137 	tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7138 
7139 	if (!coerce_template_template_parms
7140 	    (parmparm, argparm, complain, in_decl, outer_args))
7141 	  return 0;
7142       }
7143       /* Fall through.  */
7144 
7145     case TYPE_DECL:
7146       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7147 	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7148 	/* Argument is a parameter pack but parameter is not.  */
7149 	return 0;
7150       break;
7151 
7152     case PARM_DECL:
7153       /* The tsubst call is used to handle cases such as
7154 
7155            template <int> class C {};
7156 	   template <class T, template <T> class TT> class D {};
7157 	   D<int, C> d;
7158 
7159 	 i.e. the parameter list of TT depends on earlier parameters.  */
7160       if (!uses_template_parms (TREE_TYPE (arg)))
7161 	{
7162 	  tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7163 	  if (!uses_template_parms (t)
7164 	      && !same_type_p (t, TREE_TYPE (arg)))
7165 	    return 0;
7166 	}
7167 
7168       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7169 	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7170 	/* Argument is a parameter pack but parameter is not.  */
7171 	return 0;
7172 
7173       break;
7174 
7175     default:
7176       gcc_unreachable ();
7177     }
7178 
7179   return 1;
7180 }
7181 
7182 /* Coerce template argument list ARGLIST for use with template
7183    template-parameter TEMPL.  */
7184 
7185 static tree
7186 coerce_template_args_for_ttp (tree templ, tree arglist,
7187 			      tsubst_flags_t complain)
7188 {
7189   /* Consider an example where a template template parameter declared as
7190 
7191      template <class T, class U = std::allocator<T> > class TT
7192 
7193      The template parameter level of T and U are one level larger than
7194      of TT.  To proper process the default argument of U, say when an
7195      instantiation `TT<int>' is seen, we need to build the full
7196      arguments containing {int} as the innermost level.  Outer levels,
7197      available when not appearing as default template argument, can be
7198      obtained from the arguments of the enclosing template.
7199 
7200      Suppose that TT is later substituted with std::vector.  The above
7201      instantiation is `TT<int, std::allocator<T> >' with TT at
7202      level 1, and T at level 2, while the template arguments at level 1
7203      becomes {std::vector} and the inner level 2 is {int}.  */
7204 
7205   tree outer = DECL_CONTEXT (templ);
7206   if (outer)
7207     {
7208       if (DECL_TEMPLATE_SPECIALIZATION (outer))
7209 	/* We want arguments for the partial specialization, not arguments for
7210 	   the primary template.  */
7211 	outer = template_parms_to_args (DECL_TEMPLATE_PARMS (outer));
7212       else
7213 	outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7214     }
7215   else if (current_template_parms)
7216     {
7217       /* This is an argument of the current template, so we haven't set
7218 	 DECL_CONTEXT yet.  */
7219       tree relevant_template_parms;
7220 
7221       /* Parameter levels that are greater than the level of the given
7222 	 template template parm are irrelevant.  */
7223       relevant_template_parms = current_template_parms;
7224       while (TMPL_PARMS_DEPTH (relevant_template_parms)
7225 	     != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7226 	relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7227 
7228       outer = template_parms_to_args (relevant_template_parms);
7229     }
7230 
7231   if (outer)
7232     arglist = add_to_template_args (outer, arglist);
7233 
7234   tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7235   return coerce_template_parms (parmlist, arglist, templ,
7236 				complain,
7237 				/*require_all_args=*/true,
7238 				/*use_default_args=*/true);
7239 }
7240 
7241 /* A cache of template template parameters with match-all default
7242    arguments.  */
7243 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7244 static void
7245 store_defaulted_ttp (tree v, tree t)
7246 {
7247   if (!defaulted_ttp_cache)
7248     defaulted_ttp_cache = hash_map<tree,tree>::create_ggc (13);
7249   defaulted_ttp_cache->put (v, t);
7250 }
7251 static tree
7252 lookup_defaulted_ttp (tree v)
7253 {
7254   if (defaulted_ttp_cache)
7255     if (tree *p = defaulted_ttp_cache->get (v))
7256       return *p;
7257   return NULL_TREE;
7258 }
7259 
7260 /* T is a bound template template-parameter.  Copy its arguments into default
7261    arguments of the template template-parameter's template parameters.  */
7262 
7263 static tree
7264 add_defaults_to_ttp (tree otmpl)
7265 {
7266   if (tree c = lookup_defaulted_ttp (otmpl))
7267     return c;
7268 
7269   tree ntmpl = copy_node (otmpl);
7270 
7271   tree ntype = copy_node (TREE_TYPE (otmpl));
7272   TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7273   TYPE_MAIN_VARIANT (ntype) = ntype;
7274   TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7275   TYPE_NAME (ntype) = ntmpl;
7276   SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7277 
7278   tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7279     = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7280   TEMPLATE_PARM_DECL (idx) = ntmpl;
7281   TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7282 
7283   tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7284   tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7285   TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7286   tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7287   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7288     {
7289       tree o = TREE_VEC_ELT (vec, i);
7290       if (!template_parameter_pack_p (TREE_VALUE (o)))
7291 	{
7292 	  tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7293 	  TREE_PURPOSE (n) = any_targ_node;
7294 	}
7295     }
7296 
7297   store_defaulted_ttp (otmpl, ntmpl);
7298   return ntmpl;
7299 }
7300 
7301 /* ARG is a bound potential template template-argument, and PARGS is a list
7302    of arguments for the corresponding template template-parameter.  Adjust
7303    PARGS as appropriate for application to ARG's template, and if ARG is a
7304    BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7305    arguments to the template template parameter.  */
7306 
7307 static tree
7308 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7309 {
7310   ++processing_template_decl;
7311   tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7312   if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7313     {
7314       /* When comparing two template template-parameters in partial ordering,
7315 	 rewrite the one currently being used as an argument to have default
7316 	 arguments for all parameters.  */
7317       arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7318       pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7319       if (pargs != error_mark_node)
7320 	arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7321 					   TYPE_TI_ARGS (arg));
7322     }
7323   else
7324     {
7325       tree aparms
7326 	= INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7327       pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7328 				       /*require_all*/true,
7329 				       /*use_default*/true);
7330     }
7331   --processing_template_decl;
7332   return pargs;
7333 }
7334 
7335 /* Subroutine of unify for the case when PARM is a
7336    BOUND_TEMPLATE_TEMPLATE_PARM.  */
7337 
7338 static int
7339 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7340 		      bool explain_p)
7341 {
7342   tree parmvec = TYPE_TI_ARGS (parm);
7343   tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7344 
7345   /* The template template parm might be variadic and the argument
7346      not, so flatten both argument lists.  */
7347   parmvec = expand_template_argument_pack (parmvec);
7348   argvec = expand_template_argument_pack (argvec);
7349 
7350   if (flag_new_ttp)
7351     {
7352       /* In keeping with P0522R0, adjust P's template arguments
7353 	 to apply to A's template; then flatten it again.  */
7354       tree nparmvec = parmvec;
7355       nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7356       nparmvec = expand_template_argument_pack (nparmvec);
7357 
7358       if (unify (tparms, targs, nparmvec, argvec,
7359 		 UNIFY_ALLOW_NONE, explain_p))
7360 	return 1;
7361 
7362       /* If the P0522 adjustment eliminated a pack expansion, deduce
7363 	 empty packs.  */
7364       if (flag_new_ttp
7365 	  && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7366 	  && unify_pack_expansion (tparms, targs, parmvec, argvec,
7367 				   DEDUCE_EXACT, /*sub*/true, explain_p))
7368 	return 1;
7369     }
7370   else
7371     {
7372       /* Deduce arguments T, i from TT<T> or TT<i>.
7373 	 We check each element of PARMVEC and ARGVEC individually
7374 	 rather than the whole TREE_VEC since they can have
7375 	 different number of elements, which is allowed under N2555.  */
7376 
7377       int len = TREE_VEC_LENGTH (parmvec);
7378 
7379       /* Check if the parameters end in a pack, making them
7380 	 variadic.  */
7381       int parm_variadic_p = 0;
7382       if (len > 0
7383 	  && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7384 	parm_variadic_p = 1;
7385 
7386       for (int i = 0; i < len - parm_variadic_p; ++i)
7387 	/* If the template argument list of P contains a pack
7388 	   expansion that is not the last template argument, the
7389 	   entire template argument list is a non-deduced
7390 	   context.  */
7391 	if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7392 	  return unify_success (explain_p);
7393 
7394       if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7395 	return unify_too_few_arguments (explain_p,
7396 					TREE_VEC_LENGTH (argvec), len);
7397 
7398       for (int i = 0; i < len - parm_variadic_p; ++i)
7399 	if (unify (tparms, targs,
7400 		   TREE_VEC_ELT (parmvec, i),
7401 		   TREE_VEC_ELT (argvec, i),
7402 		   UNIFY_ALLOW_NONE, explain_p))
7403 	  return 1;
7404 
7405       if (parm_variadic_p
7406 	  && unify_pack_expansion (tparms, targs,
7407 				   parmvec, argvec,
7408 				   DEDUCE_EXACT,
7409 				   /*subr=*/true, explain_p))
7410 	return 1;
7411     }
7412 
7413   return 0;
7414 }
7415 
7416 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
7417    template template parameters.  Both PARM_PARMS and ARG_PARMS are
7418    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
7419    or PARM_DECL.
7420 
7421    Consider the example:
7422      template <class T> class A;
7423      template<template <class U> class TT> class B;
7424 
7425    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
7426    the parameters to A, and OUTER_ARGS contains A.  */
7427 
7428 static int
7429 coerce_template_template_parms (tree parm_parms,
7430 				tree arg_parms,
7431 				tsubst_flags_t complain,
7432 				tree in_decl,
7433 				tree outer_args)
7434 {
7435   int nparms, nargs, i;
7436   tree parm, arg;
7437   int variadic_p = 0;
7438 
7439   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
7440   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
7441 
7442   nparms = TREE_VEC_LENGTH (parm_parms);
7443   nargs = TREE_VEC_LENGTH (arg_parms);
7444 
7445   if (flag_new_ttp)
7446     {
7447       /* P0522R0: A template template-parameter P is at least as specialized as
7448 	 a template template-argument A if, given the following rewrite to two
7449 	 function templates, the function template corresponding to P is at
7450 	 least as specialized as the function template corresponding to A
7451 	 according to the partial ordering rules for function templates
7452 	 ([temp.func.order]). Given an invented class template X with the
7453 	 template parameter list of A (including default arguments):
7454 
7455 	 * Each of the two function templates has the same template parameters,
7456 	 respectively, as P or A.
7457 
7458 	 * Each function template has a single function parameter whose type is
7459 	 a specialization of X with template arguments corresponding to the
7460 	 template parameters from the respective function template where, for
7461 	 each template parameter PP in the template parameter list of the
7462 	 function template, a corresponding template argument AA is formed. If
7463 	 PP declares a parameter pack, then AA is the pack expansion
7464 	 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
7465 
7466 	 If the rewrite produces an invalid type, then P is not at least as
7467 	 specialized as A.  */
7468 
7469       /* So coerce P's args to apply to A's parms, and then deduce between A's
7470 	 args and the converted args.  If that succeeds, A is at least as
7471 	 specialized as P, so they match.*/
7472       tree pargs = template_parms_level_to_args (parm_parms);
7473       ++processing_template_decl;
7474       pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
7475 				     /*require_all*/true, /*use_default*/true);
7476       --processing_template_decl;
7477       if (pargs != error_mark_node)
7478 	{
7479 	  tree targs = make_tree_vec (nargs);
7480 	  tree aargs = template_parms_level_to_args (arg_parms);
7481 	  if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
7482 		      /*explain*/false))
7483 	    return 1;
7484 	}
7485     }
7486 
7487   /* Determine whether we have a parameter pack at the end of the
7488      template template parameter's template parameter list.  */
7489   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
7490     {
7491       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
7492 
7493       if (error_operand_p (parm))
7494 	return 0;
7495 
7496       switch (TREE_CODE (parm))
7497         {
7498         case TEMPLATE_DECL:
7499         case TYPE_DECL:
7500           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7501             variadic_p = 1;
7502           break;
7503 
7504         case PARM_DECL:
7505           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7506             variadic_p = 1;
7507           break;
7508 
7509         default:
7510           gcc_unreachable ();
7511         }
7512     }
7513 
7514   if (nargs != nparms
7515       && !(variadic_p && nargs >= nparms - 1))
7516     return 0;
7517 
7518   /* Check all of the template parameters except the parameter pack at
7519      the end (if any).  */
7520   for (i = 0; i < nparms - variadic_p; ++i)
7521     {
7522       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
7523           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7524         continue;
7525 
7526       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7527       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7528 
7529       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7530                                           outer_args))
7531 	return 0;
7532 
7533     }
7534 
7535   if (variadic_p)
7536     {
7537       /* Check each of the template parameters in the template
7538 	 argument against the template parameter pack at the end of
7539 	 the template template parameter.  */
7540       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
7541 	return 0;
7542 
7543       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7544 
7545       for (; i < nargs; ++i)
7546         {
7547           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7548             continue;
7549 
7550           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7551 
7552           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7553                                               outer_args))
7554             return 0;
7555         }
7556     }
7557 
7558   return 1;
7559 }
7560 
7561 /* Verifies that the deduced template arguments (in TARGS) for the
7562    template template parameters (in TPARMS) represent valid bindings,
7563    by comparing the template parameter list of each template argument
7564    to the template parameter list of its corresponding template
7565    template parameter, in accordance with DR150. This
7566    routine can only be called after all template arguments have been
7567    deduced. It will return TRUE if all of the template template
7568    parameter bindings are okay, FALSE otherwise.  */
7569 bool
7570 template_template_parm_bindings_ok_p (tree tparms, tree targs)
7571 {
7572   int i, ntparms = TREE_VEC_LENGTH (tparms);
7573   bool ret = true;
7574 
7575   /* We're dealing with template parms in this process.  */
7576   ++processing_template_decl;
7577 
7578   targs = INNERMOST_TEMPLATE_ARGS (targs);
7579 
7580   for (i = 0; i < ntparms; ++i)
7581     {
7582       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
7583       tree targ = TREE_VEC_ELT (targs, i);
7584 
7585       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
7586 	{
7587 	  tree packed_args = NULL_TREE;
7588 	  int idx, len = 1;
7589 
7590 	  if (ARGUMENT_PACK_P (targ))
7591 	    {
7592 	      /* Look inside the argument pack.  */
7593 	      packed_args = ARGUMENT_PACK_ARGS (targ);
7594 	      len = TREE_VEC_LENGTH (packed_args);
7595 	    }
7596 
7597 	  for (idx = 0; idx < len; ++idx)
7598 	    {
7599 	      tree targ_parms = NULL_TREE;
7600 
7601 	      if (packed_args)
7602 		/* Extract the next argument from the argument
7603 		   pack.  */
7604 		targ = TREE_VEC_ELT (packed_args, idx);
7605 
7606 	      if (PACK_EXPANSION_P (targ))
7607 		/* Look at the pattern of the pack expansion.  */
7608 		targ = PACK_EXPANSION_PATTERN (targ);
7609 
7610 	      /* Extract the template parameters from the template
7611 		 argument.  */
7612 	      if (TREE_CODE (targ) == TEMPLATE_DECL)
7613 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
7614 	      else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
7615 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
7616 
7617 	      /* Verify that we can coerce the template template
7618 		 parameters from the template argument to the template
7619 		 parameter.  This requires an exact match.  */
7620 	      if (targ_parms
7621 		  && !coerce_template_template_parms
7622 		       (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
7623 			targ_parms,
7624 			tf_none,
7625 			tparm,
7626 			targs))
7627 		{
7628 		  ret = false;
7629 		  goto out;
7630 		}
7631 	    }
7632 	}
7633     }
7634 
7635  out:
7636 
7637   --processing_template_decl;
7638   return ret;
7639 }
7640 
7641 /* Since type attributes aren't mangled, we need to strip them from
7642    template type arguments.  */
7643 
7644 static tree
7645 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
7646 {
7647   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
7648     return arg;
7649   bool removed_attributes = false;
7650   tree canon = strip_typedefs (arg, &removed_attributes);
7651   if (removed_attributes
7652       && (complain & tf_warning))
7653     warning (OPT_Wignored_attributes,
7654 	     "ignoring attributes on template argument %qT", arg);
7655   return canon;
7656 }
7657 
7658 /* And from inside dependent non-type arguments like sizeof(Type).  */
7659 
7660 static tree
7661 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
7662 {
7663   if (!arg || arg == error_mark_node)
7664     return arg;
7665   bool removed_attributes = false;
7666   tree canon = strip_typedefs_expr (arg, &removed_attributes);
7667   if (removed_attributes
7668       && (complain & tf_warning))
7669     warning (OPT_Wignored_attributes,
7670 	     "ignoring attributes in template argument %qE", arg);
7671   return canon;
7672 }
7673 
7674 // A template declaration can be substituted for a constrained
7675 // template template parameter only when the argument is more
7676 // constrained than the parameter.
7677 static bool
7678 is_compatible_template_arg (tree parm, tree arg)
7679 {
7680   tree parm_cons = get_constraints (parm);
7681 
7682   /* For now, allow constrained template template arguments
7683      and unconstrained template template parameters.  */
7684   if (parm_cons == NULL_TREE)
7685     return true;
7686 
7687   tree arg_cons = get_constraints (arg);
7688 
7689   // If the template parameter is constrained, we need to rewrite its
7690   // constraints in terms of the ARG's template parameters. This ensures
7691   // that all of the template parameter types will have the same depth.
7692   //
7693   // Note that this is only valid when coerce_template_template_parm is
7694   // true for the innermost template parameters of PARM and ARG. In other
7695   // words, because coercion is successful, this conversion will be valid.
7696   if (parm_cons)
7697     {
7698       tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (arg));
7699       parm_cons = tsubst_constraint_info (parm_cons,
7700 					  INNERMOST_TEMPLATE_ARGS (args),
7701 					  tf_none, NULL_TREE);
7702       if (parm_cons == error_mark_node)
7703         return false;
7704     }
7705 
7706   return subsumes (parm_cons, arg_cons);
7707 }
7708 
7709 // Convert a placeholder argument into a binding to the original
7710 // parameter. The original parameter is saved as the TREE_TYPE of
7711 // ARG.
7712 static inline tree
7713 convert_wildcard_argument (tree parm, tree arg)
7714 {
7715   TREE_TYPE (arg) = parm;
7716   return arg;
7717 }
7718 
7719 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
7720    because one of them is dependent.  But we need to represent the
7721    conversion for the benefit of cp_tree_equal.  */
7722 
7723 static tree
7724 maybe_convert_nontype_argument (tree type, tree arg)
7725 {
7726   /* Auto parms get no conversion.  */
7727   if (type_uses_auto (type))
7728     return arg;
7729   /* We don't need or want to add this conversion now if we're going to use the
7730      argument for deduction.  */
7731   if (value_dependent_expression_p (arg))
7732     return arg;
7733 
7734   type = cv_unqualified (type);
7735   tree argtype = TREE_TYPE (arg);
7736   if (same_type_p (type, argtype))
7737     return arg;
7738 
7739   arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
7740   IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
7741   return arg;
7742 }
7743 
7744 /* Convert the indicated template ARG as necessary to match the
7745    indicated template PARM.  Returns the converted ARG, or
7746    error_mark_node if the conversion was unsuccessful.  Error and
7747    warning messages are issued under control of COMPLAIN.  This
7748    conversion is for the Ith parameter in the parameter list.  ARGS is
7749    the full set of template arguments deduced so far.  */
7750 
7751 static tree
7752 convert_template_argument (tree parm,
7753 			   tree arg,
7754 			   tree args,
7755 			   tsubst_flags_t complain,
7756 			   int i,
7757 			   tree in_decl)
7758 {
7759   tree orig_arg;
7760   tree val;
7761   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
7762 
7763   if (parm == error_mark_node)
7764     return error_mark_node;
7765 
7766   /* Trivially convert placeholders. */
7767   if (TREE_CODE (arg) == WILDCARD_DECL)
7768     return convert_wildcard_argument (parm, arg);
7769 
7770   if (arg == any_targ_node)
7771     return arg;
7772 
7773   if (TREE_CODE (arg) == TREE_LIST
7774       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
7775     {
7776       /* The template argument was the name of some
7777 	 member function.  That's usually
7778 	 invalid, but static members are OK.  In any
7779 	 case, grab the underlying fields/functions
7780 	 and issue an error later if required.  */
7781       orig_arg = TREE_VALUE (arg);
7782       TREE_TYPE (arg) = unknown_type_node;
7783     }
7784 
7785   orig_arg = arg;
7786 
7787   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
7788   requires_type = (TREE_CODE (parm) == TYPE_DECL
7789 		   || requires_tmpl_type);
7790 
7791   /* When determining whether an argument pack expansion is a template,
7792      look at the pattern.  */
7793   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
7794     arg = PACK_EXPANSION_PATTERN (arg);
7795 
7796   /* Deal with an injected-class-name used as a template template arg.  */
7797   if (requires_tmpl_type && CLASS_TYPE_P (arg))
7798     {
7799       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
7800       if (TREE_CODE (t) == TEMPLATE_DECL)
7801 	{
7802 	  if (cxx_dialect >= cxx11)
7803 	    /* OK under DR 1004.  */;
7804 	  else if (complain & tf_warning_or_error)
7805 	    pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
7806 		     " used as template template argument", TYPE_NAME (arg));
7807 	  else if (flag_pedantic_errors)
7808 	    t = arg;
7809 
7810 	  arg = t;
7811 	}
7812     }
7813 
7814   is_tmpl_type =
7815     ((TREE_CODE (arg) == TEMPLATE_DECL
7816       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
7817      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
7818      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7819      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
7820 
7821   if (is_tmpl_type
7822       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7823 	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
7824     arg = TYPE_STUB_DECL (arg);
7825 
7826   is_type = TYPE_P (arg) || is_tmpl_type;
7827 
7828   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
7829       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
7830     {
7831       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
7832 	{
7833 	  if (complain & tf_error)
7834 	    error ("invalid use of destructor %qE as a type", orig_arg);
7835 	  return error_mark_node;
7836 	}
7837 
7838       permerror (input_location,
7839 		 "to refer to a type member of a template parameter, "
7840 		 "use %<typename %E%>", orig_arg);
7841 
7842       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
7843 				     TREE_OPERAND (arg, 1),
7844 				     typename_type,
7845 				     complain);
7846       arg = orig_arg;
7847       is_type = 1;
7848     }
7849   if (is_type != requires_type)
7850     {
7851       if (in_decl)
7852 	{
7853 	  if (complain & tf_error)
7854 	    {
7855 	      error ("type/value mismatch at argument %d in template "
7856 		     "parameter list for %qD",
7857 		     i + 1, in_decl);
7858 	      if (is_type)
7859 		inform (input_location,
7860 			"  expected a constant of type %qT, got %qT",
7861 			TREE_TYPE (parm),
7862 			(DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
7863 	      else if (requires_tmpl_type)
7864 		inform (input_location,
7865 			"  expected a class template, got %qE", orig_arg);
7866 	      else
7867 		inform (input_location,
7868 			"  expected a type, got %qE", orig_arg);
7869 	    }
7870 	}
7871       return error_mark_node;
7872     }
7873   if (is_tmpl_type ^ requires_tmpl_type)
7874     {
7875       if (in_decl && (complain & tf_error))
7876 	{
7877 	  error ("type/value mismatch at argument %d in template "
7878 		 "parameter list for %qD",
7879 		 i + 1, in_decl);
7880 	  if (is_tmpl_type)
7881 	    inform (input_location,
7882 		    "  expected a type, got %qT", DECL_NAME (arg));
7883 	  else
7884 	    inform (input_location,
7885 		    "  expected a class template, got %qT", orig_arg);
7886 	}
7887       return error_mark_node;
7888     }
7889 
7890   if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
7891     /* We already did the appropriate conversion when packing args.  */
7892     val = orig_arg;
7893   else if (is_type)
7894     {
7895       if (requires_tmpl_type)
7896 	{
7897 	  if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
7898 	    /* The number of argument required is not known yet.
7899 	       Just accept it for now.  */
7900 	    val = orig_arg;
7901 	  else
7902 	    {
7903 	      tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7904 	      tree argparm;
7905 
7906 	      /* Strip alias templates that are equivalent to another
7907 		 template.  */
7908 	      arg = get_underlying_template (arg);
7909               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7910 
7911 	      if (coerce_template_template_parms (parmparm, argparm,
7912 						  complain, in_decl,
7913 						  args))
7914 		{
7915 		  val = arg;
7916 
7917 		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
7918 		     TEMPLATE_DECL.  */
7919 		  if (val != error_mark_node)
7920                     {
7921                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
7922                         val = TREE_TYPE (val);
7923 		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
7924 			val = make_pack_expansion (val, complain);
7925                     }
7926 		}
7927 	      else
7928 		{
7929 		  if (in_decl && (complain & tf_error))
7930 		    {
7931 		      error ("type/value mismatch at argument %d in "
7932 			     "template parameter list for %qD",
7933 			     i + 1, in_decl);
7934 		      inform (input_location,
7935 			      "  expected a template of type %qD, got %qT",
7936 			      parm, orig_arg);
7937 		    }
7938 
7939 		  val = error_mark_node;
7940 		}
7941 
7942               // Check that the constraints are compatible before allowing the
7943               // substitution.
7944               if (val != error_mark_node)
7945                 if (!is_compatible_template_arg (parm, arg))
7946                   {
7947 		    if (in_decl && (complain & tf_error))
7948                       {
7949                         error ("constraint mismatch at argument %d in "
7950                                "template parameter list for %qD",
7951                                i + 1, in_decl);
7952                         inform (input_location, "  expected %qD but got %qD",
7953                                 parm, arg);
7954                       }
7955 		    val = error_mark_node;
7956                   }
7957 	    }
7958 	}
7959       else
7960 	val = orig_arg;
7961       /* We only form one instance of each template specialization.
7962 	 Therefore, if we use a non-canonical variant (i.e., a
7963 	 typedef), any future messages referring to the type will use
7964 	 the typedef, which is confusing if those future uses do not
7965 	 themselves also use the typedef.  */
7966       if (TYPE_P (val))
7967 	val = canonicalize_type_argument (val, complain);
7968     }
7969   else
7970     {
7971       tree t = TREE_TYPE (parm);
7972 
7973       if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
7974 	  > TMPL_ARGS_DEPTH (args))
7975 	/* We don't have enough levels of args to do any substitution.  This
7976 	   can happen in the context of -fnew-ttp-matching.  */;
7977       else if (tree a = type_uses_auto (t))
7978 	{
7979 	  t = do_auto_deduction (t, arg, a, complain, adc_unify, args);
7980 	  if (t == error_mark_node)
7981 	    return error_mark_node;
7982 	}
7983       else
7984 	t = tsubst (t, args, complain, in_decl);
7985 
7986       if (invalid_nontype_parm_type_p (t, complain))
7987 	return error_mark_node;
7988 
7989       if (!type_dependent_expression_p (orig_arg)
7990 	  && !uses_template_parms (t))
7991 	/* We used to call digest_init here.  However, digest_init
7992 	   will report errors, which we don't want when complain
7993 	   is zero.  More importantly, digest_init will try too
7994 	   hard to convert things: for example, `0' should not be
7995 	   converted to pointer type at this point according to
7996 	   the standard.  Accepting this is not merely an
7997 	   extension, since deciding whether or not these
7998 	   conversions can occur is part of determining which
7999 	   function template to call, or whether a given explicit
8000 	   argument specification is valid.  */
8001 	val = convert_nontype_argument (t, orig_arg, complain);
8002       else
8003 	{
8004 	  val = canonicalize_expr_argument (orig_arg, complain);
8005 	  val = maybe_convert_nontype_argument (t, val);
8006 	}
8007 
8008 
8009       if (val == NULL_TREE)
8010 	val = error_mark_node;
8011       else if (val == error_mark_node && (complain & tf_error))
8012 	error ("could not convert template argument %qE from %qT to %qT",
8013 	       orig_arg, TREE_TYPE (orig_arg), t);
8014 
8015       if (INDIRECT_REF_P (val))
8016         {
8017           /* Reject template arguments that are references to built-in
8018              functions with no library fallbacks.  */
8019           const_tree inner = TREE_OPERAND (val, 0);
8020 	  const_tree innertype = TREE_TYPE (inner);
8021 	  if (innertype
8022 	      && TREE_CODE (innertype) == REFERENCE_TYPE
8023 	      && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8024 	      && TREE_OPERAND_LENGTH (inner) > 0
8025               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8026               return error_mark_node;
8027         }
8028 
8029       if (TREE_CODE (val) == SCOPE_REF)
8030 	{
8031 	  /* Strip typedefs from the SCOPE_REF.  */
8032 	  tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8033 	  tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8034 						   complain);
8035 	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8036 				      QUALIFIED_NAME_IS_TEMPLATE (val));
8037 	}
8038     }
8039 
8040   return val;
8041 }
8042 
8043 /* Coerces the remaining template arguments in INNER_ARGS (from
8044    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8045    Returns the coerced argument pack. PARM_IDX is the position of this
8046    parameter in the template parameter list. ARGS is the original
8047    template argument list.  */
8048 static tree
8049 coerce_template_parameter_pack (tree parms,
8050                                 int parm_idx,
8051                                 tree args,
8052                                 tree inner_args,
8053                                 int arg_idx,
8054                                 tree new_args,
8055                                 int* lost,
8056                                 tree in_decl,
8057                                 tsubst_flags_t complain)
8058 {
8059   tree parm = TREE_VEC_ELT (parms, parm_idx);
8060   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8061   tree packed_args;
8062   tree argument_pack;
8063   tree packed_parms = NULL_TREE;
8064 
8065   if (arg_idx > nargs)
8066     arg_idx = nargs;
8067 
8068   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8069     {
8070       /* When the template parameter is a non-type template parameter pack
8071          or template template parameter pack whose type or template
8072          parameters use parameter packs, we know exactly how many arguments
8073          we are looking for.  Build a vector of the instantiated decls for
8074          these template parameters in PACKED_PARMS.  */
8075       /* We can't use make_pack_expansion here because it would interpret a
8076 	 _DECL as a use rather than a declaration.  */
8077       tree decl = TREE_VALUE (parm);
8078       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8079       SET_PACK_EXPANSION_PATTERN (exp, decl);
8080       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8081       SET_TYPE_STRUCTURAL_EQUALITY (exp);
8082 
8083       TREE_VEC_LENGTH (args)--;
8084       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8085       TREE_VEC_LENGTH (args)++;
8086 
8087       if (packed_parms == error_mark_node)
8088         return error_mark_node;
8089 
8090       /* If we're doing a partial instantiation of a member template,
8091          verify that all of the types used for the non-type
8092          template parameter pack are, in fact, valid for non-type
8093          template parameters.  */
8094       if (arg_idx < nargs
8095           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8096         {
8097           int j, len = TREE_VEC_LENGTH (packed_parms);
8098           for (j = 0; j < len; ++j)
8099             {
8100               tree t = TREE_TYPE (TREE_VEC_ELT (packed_parms, j));
8101               if (invalid_nontype_parm_type_p (t, complain))
8102                 return error_mark_node;
8103             }
8104 	  /* We don't know how many args we have yet, just
8105 	     use the unconverted ones for now.  */
8106 	  return NULL_TREE;
8107         }
8108 
8109       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8110     }
8111   /* Check if we have a placeholder pack, which indicates we're
8112      in the context of a introduction list.  In that case we want
8113      to match this pack to the single placeholder.  */
8114   else if (arg_idx < nargs
8115            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8116            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8117     {
8118       nargs = arg_idx + 1;
8119       packed_args = make_tree_vec (1);
8120     }
8121   else
8122     packed_args = make_tree_vec (nargs - arg_idx);
8123 
8124   /* Convert the remaining arguments, which will be a part of the
8125      parameter pack "parm".  */
8126   int first_pack_arg = arg_idx;
8127   for (; arg_idx < nargs; ++arg_idx)
8128     {
8129       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8130       tree actual_parm = TREE_VALUE (parm);
8131       int pack_idx = arg_idx - first_pack_arg;
8132 
8133       if (packed_parms)
8134         {
8135 	  /* Once we've packed as many args as we have types, stop.  */
8136 	  if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8137 	    break;
8138 	  else if (PACK_EXPANSION_P (arg))
8139 	    /* We don't know how many args we have yet, just
8140 	       use the unconverted ones for now.  */
8141 	    return NULL_TREE;
8142 	  else
8143 	    actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8144         }
8145 
8146       if (arg == error_mark_node)
8147 	{
8148 	  if (complain & tf_error)
8149 	    error ("template argument %d is invalid", arg_idx + 1);
8150 	}
8151       else
8152 	arg = convert_template_argument (actual_parm,
8153 					 arg, new_args, complain, parm_idx,
8154 					 in_decl);
8155       if (arg == error_mark_node)
8156         (*lost)++;
8157       TREE_VEC_ELT (packed_args, pack_idx) = arg;
8158     }
8159 
8160   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8161       && TREE_VEC_LENGTH (packed_args) > 0)
8162     {
8163       if (complain & tf_error)
8164 	error ("wrong number of template arguments (%d, should be %d)",
8165 	       arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8166       return error_mark_node;
8167     }
8168 
8169   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8170       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8171     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8172   else
8173     {
8174       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8175       TREE_CONSTANT (argument_pack) = 1;
8176     }
8177 
8178   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8179   if (CHECKING_P)
8180     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8181 					 TREE_VEC_LENGTH (packed_args));
8182   return argument_pack;
8183 }
8184 
8185 /* Returns the number of pack expansions in the template argument vector
8186    ARGS.  */
8187 
8188 static int
8189 pack_expansion_args_count (tree args)
8190 {
8191   int i;
8192   int count = 0;
8193   if (args)
8194     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8195       {
8196 	tree elt = TREE_VEC_ELT (args, i);
8197 	if (elt && PACK_EXPANSION_P (elt))
8198 	  ++count;
8199       }
8200   return count;
8201 }
8202 
8203 /* Convert all template arguments to their appropriate types, and
8204    return a vector containing the innermost resulting template
8205    arguments.  If any error occurs, return error_mark_node. Error and
8206    warning messages are issued under control of COMPLAIN.
8207 
8208    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8209    for arguments not specified in ARGS.  Otherwise, if
8210    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8211    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
8212    USE_DEFAULT_ARGS is false, then all arguments must be specified in
8213    ARGS.  */
8214 
8215 static tree
8216 coerce_template_parms (tree parms,
8217 		       tree args,
8218 		       tree in_decl,
8219 		       tsubst_flags_t complain,
8220 		       bool require_all_args,
8221 		       bool use_default_args)
8222 {
8223   int nparms, nargs, parm_idx, arg_idx, lost = 0;
8224   tree orig_inner_args;
8225   tree inner_args;
8226   tree new_args;
8227   tree new_inner_args;
8228   int saved_unevaluated_operand;
8229   int saved_inhibit_evaluation_warnings;
8230 
8231   /* When used as a boolean value, indicates whether this is a
8232      variadic template parameter list. Since it's an int, we can also
8233      subtract it from nparms to get the number of non-variadic
8234      parameters.  */
8235   int variadic_p = 0;
8236   int variadic_args_p = 0;
8237   int post_variadic_parms = 0;
8238 
8239   /* Adjustment to nparms for fixed parameter packs.  */
8240   int fixed_pack_adjust = 0;
8241   int fixed_packs = 0;
8242   int missing = 0;
8243 
8244   /* Likewise for parameters with default arguments.  */
8245   int default_p = 0;
8246 
8247   if (args == error_mark_node)
8248     return error_mark_node;
8249 
8250   nparms = TREE_VEC_LENGTH (parms);
8251 
8252   /* Determine if there are any parameter packs or default arguments.  */
8253   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8254     {
8255       tree parm = TREE_VEC_ELT (parms, parm_idx);
8256       if (variadic_p)
8257 	++post_variadic_parms;
8258       if (template_parameter_pack_p (TREE_VALUE (parm)))
8259 	++variadic_p;
8260       if (TREE_PURPOSE (parm))
8261 	++default_p;
8262     }
8263 
8264   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8265   /* If there are no parameters that follow a parameter pack, we need to
8266      expand any argument packs so that we can deduce a parameter pack from
8267      some non-packed args followed by an argument pack, as in variadic85.C.
8268      If there are such parameters, we need to leave argument packs intact
8269      so the arguments are assigned properly.  This can happen when dealing
8270      with a nested class inside a partial specialization of a class
8271      template, as in variadic92.C, or when deducing a template parameter pack
8272      from a sub-declarator, as in variadic114.C.  */
8273   if (!post_variadic_parms)
8274     inner_args = expand_template_argument_pack (inner_args);
8275 
8276   /* Count any pack expansion args.  */
8277   variadic_args_p = pack_expansion_args_count (inner_args);
8278 
8279   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8280   if ((nargs - variadic_args_p > nparms && !variadic_p)
8281       || (nargs < nparms - variadic_p
8282 	  && require_all_args
8283 	  && !variadic_args_p
8284 	  && (!use_default_args
8285 	      || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8286                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8287     {
8288     bad_nargs:
8289       if (complain & tf_error)
8290 	{
8291           if (variadic_p || default_p)
8292             {
8293               nparms -= variadic_p + default_p;
8294 	      error ("wrong number of template arguments "
8295 		     "(%d, should be at least %d)", nargs, nparms);
8296             }
8297 	  else
8298 	     error ("wrong number of template arguments "
8299 		    "(%d, should be %d)", nargs, nparms);
8300 
8301 	  if (in_decl)
8302 	    inform (DECL_SOURCE_LOCATION (in_decl),
8303 		    "provided for %qD", in_decl);
8304 	}
8305 
8306       return error_mark_node;
8307     }
8308   /* We can't pass a pack expansion to a non-pack parameter of an alias
8309      template (DR 1430).  */
8310   else if (in_decl
8311 	   && (DECL_ALIAS_TEMPLATE_P (in_decl)
8312 	       || concept_template_p (in_decl))
8313 	   && variadic_args_p
8314 	   && nargs - variadic_args_p < nparms - variadic_p)
8315     {
8316       if (complain & tf_error)
8317 	{
8318 	  for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8319 	    {
8320 	      tree arg = TREE_VEC_ELT (inner_args, i);
8321 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8322 
8323 	      if (PACK_EXPANSION_P (arg)
8324 		  && !template_parameter_pack_p (parm))
8325 		{
8326 		  if (DECL_ALIAS_TEMPLATE_P (in_decl))
8327 		    error_at (location_of (arg),
8328 			      "pack expansion argument for non-pack parameter "
8329 			      "%qD of alias template %qD", parm, in_decl);
8330 		  else
8331 		    error_at (location_of (arg),
8332 			      "pack expansion argument for non-pack parameter "
8333 			      "%qD of concept %qD", parm, in_decl);
8334 		  inform (DECL_SOURCE_LOCATION (parm), "declared here");
8335 		  goto found;
8336 		}
8337 	    }
8338 	  gcc_unreachable ();
8339 	found:;
8340 	}
8341       return error_mark_node;
8342     }
8343 
8344   /* We need to evaluate the template arguments, even though this
8345      template-id may be nested within a "sizeof".  */
8346   saved_unevaluated_operand = cp_unevaluated_operand;
8347   cp_unevaluated_operand = 0;
8348   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8349   c_inhibit_evaluation_warnings = 0;
8350   new_inner_args = make_tree_vec (nparms);
8351   new_args = add_outermost_template_args (args, new_inner_args);
8352   int pack_adjust = 0;
8353   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
8354     {
8355       tree arg;
8356       tree parm;
8357 
8358       /* Get the Ith template parameter.  */
8359       parm = TREE_VEC_ELT (parms, parm_idx);
8360 
8361       if (parm == error_mark_node)
8362 	{
8363 	  TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
8364 	  continue;
8365 	}
8366 
8367       /* Calculate the next argument.  */
8368       if (arg_idx < nargs)
8369 	arg = TREE_VEC_ELT (inner_args, arg_idx);
8370       else
8371 	arg = NULL_TREE;
8372 
8373       if (template_parameter_pack_p (TREE_VALUE (parm))
8374 	  && !(arg && ARGUMENT_PACK_P (arg)))
8375         {
8376 	  /* Some arguments will be placed in the
8377 	     template parameter pack PARM.  */
8378 	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
8379 						inner_args, arg_idx,
8380 						new_args, &lost,
8381 						in_decl, complain);
8382 
8383 	  if (arg == NULL_TREE)
8384 	    {
8385 	      /* We don't know how many args we have yet, just use the
8386 		 unconverted (and still packed) ones for now.  */
8387 	      new_inner_args = orig_inner_args;
8388 	      arg_idx = nargs;
8389 	      break;
8390 	    }
8391 
8392           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
8393 
8394           /* Store this argument.  */
8395           if (arg == error_mark_node)
8396 	    {
8397 	      lost++;
8398 	      /* We are done with all of the arguments.  */
8399 	      arg_idx = nargs;
8400 	      break;
8401 	    }
8402 	  else
8403 	    {
8404 	      pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
8405 	      arg_idx += pack_adjust;
8406 	      if (fixed_parameter_pack_p (TREE_VALUE (parm)))
8407 		{
8408 		  ++fixed_packs;
8409 		  fixed_pack_adjust += pack_adjust;
8410 		}
8411 	    }
8412 
8413           continue;
8414         }
8415       else if (arg)
8416 	{
8417           if (PACK_EXPANSION_P (arg))
8418             {
8419 	      /* "If every valid specialization of a variadic template
8420 		 requires an empty template parameter pack, the template is
8421 		 ill-formed, no diagnostic required."  So check that the
8422 		 pattern works with this parameter.  */
8423 	      tree pattern = PACK_EXPANSION_PATTERN (arg);
8424 	      tree conv = convert_template_argument (TREE_VALUE (parm),
8425 						     pattern, new_args,
8426 						     complain, parm_idx,
8427 						     in_decl);
8428 	      if (conv == error_mark_node)
8429 		{
8430 		  if (complain & tf_error)
8431 		    inform (input_location, "so any instantiation with a "
8432 			    "non-empty parameter pack would be ill-formed");
8433 		  ++lost;
8434 		}
8435 	      else if (TYPE_P (conv) && !TYPE_P (pattern))
8436 		/* Recover from missing typename.  */
8437 		TREE_VEC_ELT (inner_args, arg_idx)
8438 		  = make_pack_expansion (conv, complain);
8439 
8440               /* We don't know how many args we have yet, just
8441                  use the unconverted ones for now.  */
8442               new_inner_args = inner_args;
8443 	      arg_idx = nargs;
8444               break;
8445             }
8446         }
8447       else if (require_all_args)
8448 	{
8449 	  /* There must be a default arg in this case.  */
8450 	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
8451 				     complain, in_decl);
8452 	  /* The position of the first default template argument,
8453 	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
8454 	     Record that.  */
8455 	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8456 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8457 						 arg_idx - pack_adjust);
8458 	}
8459       else
8460 	break;
8461 
8462       if (arg == error_mark_node)
8463 	{
8464 	  if (complain & tf_error)
8465 	    error ("template argument %d is invalid", arg_idx + 1);
8466 	}
8467       else if (!arg)
8468 	{
8469 	  /* This can occur if there was an error in the template
8470 	     parameter list itself (which we would already have
8471 	     reported) that we are trying to recover from, e.g., a class
8472 	     template with a parameter list such as
8473 	     template<typename..., typename> (cpp0x/variadic150.C).  */
8474 	  ++lost;
8475 
8476 	  /* This can also happen with a fixed parameter pack (71834).  */
8477 	  if (arg_idx >= nargs)
8478 	    ++missing;
8479 	}
8480       else
8481 	arg = convert_template_argument (TREE_VALUE (parm),
8482 					 arg, new_args, complain,
8483                                          parm_idx, in_decl);
8484 
8485       if (arg == error_mark_node)
8486 	lost++;
8487       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
8488     }
8489   cp_unevaluated_operand = saved_unevaluated_operand;
8490   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8491 
8492   if (missing || arg_idx < nargs - variadic_args_p)
8493     {
8494       /* If we had fixed parameter packs, we didn't know how many arguments we
8495 	 actually needed earlier; now we do.  */
8496       nparms += fixed_pack_adjust;
8497       variadic_p -= fixed_packs;
8498       goto bad_nargs;
8499     }
8500 
8501   if (arg_idx < nargs)
8502     {
8503       /* We had some pack expansion arguments that will only work if the packs
8504 	 are empty, but wait until instantiation time to complain.
8505 	 See variadic-ttp3.C.  */
8506       int len = nparms + (nargs - arg_idx);
8507       tree args = make_tree_vec (len);
8508       int i = 0;
8509       for (; i < nparms; ++i)
8510 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
8511       for (; i < len; ++i, ++arg_idx)
8512 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
8513 					       arg_idx - pack_adjust);
8514       new_inner_args = args;
8515     }
8516 
8517   if (lost)
8518     {
8519       gcc_assert (!(complain & tf_error) || seen_error ());
8520       return error_mark_node;
8521     }
8522 
8523   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8524     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8525 					 TREE_VEC_LENGTH (new_inner_args));
8526 
8527   return new_inner_args;
8528 }
8529 
8530 /* Convert all template arguments to their appropriate types, and
8531    return a vector containing the innermost resulting template
8532    arguments.  If any error occurs, return error_mark_node. Error and
8533    warning messages are not issued.
8534 
8535    Note that no function argument deduction is performed, and default
8536    arguments are used to fill in unspecified arguments. */
8537 tree
8538 coerce_template_parms (tree parms, tree args, tree in_decl)
8539 {
8540   return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
8541 }
8542 
8543 /* Convert all template arguments to their appropriate type, and
8544    instantiate default arguments as needed. This returns a vector
8545    containing the innermost resulting template arguments, or
8546    error_mark_node if unsuccessful.  */
8547 tree
8548 coerce_template_parms (tree parms, tree args, tree in_decl,
8549                        tsubst_flags_t complain)
8550 {
8551   return coerce_template_parms (parms, args, in_decl, complain, true, true);
8552 }
8553 
8554 /* Like coerce_template_parms.  If PARMS represents all template
8555    parameters levels, this function returns a vector of vectors
8556    representing all the resulting argument levels.  Note that in this
8557    case, only the innermost arguments are coerced because the
8558    outermost ones are supposed to have been coerced already.
8559 
8560    Otherwise, if PARMS represents only (the innermost) vector of
8561    parameters, this function returns a vector containing just the
8562    innermost resulting arguments.  */
8563 
8564 static tree
8565 coerce_innermost_template_parms (tree parms,
8566 				  tree args,
8567 				  tree in_decl,
8568 				  tsubst_flags_t complain,
8569 				  bool require_all_args,
8570 				  bool use_default_args)
8571 {
8572   int parms_depth = TMPL_PARMS_DEPTH (parms);
8573   int args_depth = TMPL_ARGS_DEPTH (args);
8574   tree coerced_args;
8575 
8576   if (parms_depth > 1)
8577     {
8578       coerced_args = make_tree_vec (parms_depth);
8579       tree level;
8580       int cur_depth;
8581 
8582       for (level = parms, cur_depth = parms_depth;
8583 	   parms_depth > 0 && level != NULL_TREE;
8584 	   level = TREE_CHAIN (level), --cur_depth)
8585 	{
8586 	  tree l;
8587 	  if (cur_depth == args_depth)
8588 	    l = coerce_template_parms (TREE_VALUE (level),
8589 				       args, in_decl, complain,
8590 				       require_all_args,
8591 				       use_default_args);
8592 	  else
8593 	    l = TMPL_ARGS_LEVEL (args, cur_depth);
8594 
8595 	  if (l == error_mark_node)
8596 	    return error_mark_node;
8597 
8598 	  SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
8599 	}
8600     }
8601   else
8602     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
8603 					  args, in_decl, complain,
8604 					  require_all_args,
8605 					  use_default_args);
8606   return coerced_args;
8607 }
8608 
8609 /* Returns 1 if template args OT and NT are equivalent.  */
8610 
8611 int
8612 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
8613 {
8614   if (nt == ot)
8615     return 1;
8616   if (nt == NULL_TREE || ot == NULL_TREE)
8617     return false;
8618   if (nt == any_targ_node || ot == any_targ_node)
8619     return true;
8620 
8621   if (TREE_CODE (nt) == TREE_VEC)
8622     /* For member templates */
8623     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
8624   else if (PACK_EXPANSION_P (ot))
8625     return (PACK_EXPANSION_P (nt)
8626 	    && template_args_equal (PACK_EXPANSION_PATTERN (ot),
8627 				    PACK_EXPANSION_PATTERN (nt))
8628 	    && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
8629 				    PACK_EXPANSION_EXTRA_ARGS (nt)));
8630   else if (ARGUMENT_PACK_P (ot))
8631     {
8632       int i, len;
8633       tree opack, npack;
8634 
8635       if (!ARGUMENT_PACK_P (nt))
8636 	return 0;
8637 
8638       opack = ARGUMENT_PACK_ARGS (ot);
8639       npack = ARGUMENT_PACK_ARGS (nt);
8640       len = TREE_VEC_LENGTH (opack);
8641       if (TREE_VEC_LENGTH (npack) != len)
8642 	return 0;
8643       for (i = 0; i < len; ++i)
8644 	if (!template_args_equal (TREE_VEC_ELT (opack, i),
8645 				  TREE_VEC_ELT (npack, i)))
8646 	  return 0;
8647       return 1;
8648     }
8649   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
8650     gcc_unreachable ();
8651   else if (TYPE_P (nt))
8652     {
8653       if (!TYPE_P (ot))
8654 	return false;
8655       /* Don't treat an alias template specialization with dependent
8656 	 arguments as equivalent to its underlying type when used as a
8657 	 template argument; we need them to be distinct so that we
8658 	 substitute into the specialization arguments at instantiation
8659 	 time.  And aliases can't be equivalent without being ==, so
8660 	 we don't need to look any deeper.
8661 
8662          During partial ordering, however, we need to treat them normally so
8663          that we can order uses of the same alias with different
8664          cv-qualification (79960).  */
8665       if (!partial_order
8666 	  && (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot)))
8667 	return false;
8668       else
8669 	return same_type_p (ot, nt);
8670     }
8671   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
8672     return 0;
8673   else
8674     {
8675       /* Try to treat a template non-type argument that has been converted
8676 	 to the parameter type as equivalent to one that hasn't yet.  */
8677       for (enum tree_code code1 = TREE_CODE (ot);
8678 	   CONVERT_EXPR_CODE_P (code1)
8679 	     || code1 == NON_LVALUE_EXPR;
8680 	   code1 = TREE_CODE (ot))
8681 	ot = TREE_OPERAND (ot, 0);
8682       for (enum tree_code code2 = TREE_CODE (nt);
8683 	   CONVERT_EXPR_CODE_P (code2)
8684 	     || code2 == NON_LVALUE_EXPR;
8685 	   code2 = TREE_CODE (nt))
8686 	nt = TREE_OPERAND (nt, 0);
8687 
8688       return cp_tree_equal (ot, nt);
8689     }
8690 }
8691 
8692 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
8693    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
8694    NEWARG_PTR with the offending arguments if they are non-NULL.  */
8695 
8696 int
8697 comp_template_args (tree oldargs, tree newargs,
8698 		    tree *oldarg_ptr, tree *newarg_ptr,
8699 		    bool partial_order)
8700 {
8701   int i;
8702 
8703   if (oldargs == newargs)
8704     return 1;
8705 
8706   if (!oldargs || !newargs)
8707     return 0;
8708 
8709   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
8710     return 0;
8711 
8712   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
8713     {
8714       tree nt = TREE_VEC_ELT (newargs, i);
8715       tree ot = TREE_VEC_ELT (oldargs, i);
8716 
8717       if (! template_args_equal (ot, nt, partial_order))
8718 	{
8719 	  if (oldarg_ptr != NULL)
8720 	    *oldarg_ptr = ot;
8721 	  if (newarg_ptr != NULL)
8722 	    *newarg_ptr = nt;
8723 	  return 0;
8724 	}
8725     }
8726   return 1;
8727 }
8728 
8729 inline bool
8730 comp_template_args_porder (tree oargs, tree nargs)
8731 {
8732   return comp_template_args (oargs, nargs, NULL, NULL, true);
8733 }
8734 
8735 /* Implement a freelist interface for objects of type T.
8736 
8737    Head is a separate object, rather than a regular member, so that we
8738    can define it as a GTY deletable pointer, which is highly
8739    desirable.  A data member could be declared that way, but then the
8740    containing object would implicitly get GTY((user)), which would
8741    prevent us from instantiating freelists as global objects.
8742    Although this way we can create freelist global objects, they're
8743    such thin wrappers that instantiating temporaries at every use
8744    loses nothing and saves permanent storage for the freelist object.
8745 
8746    Member functions next, anew, poison and reinit have default
8747    implementations that work for most of the types we're interested
8748    in, but if they don't work for some type, they should be explicitly
8749    specialized.  See the comments before them for requirements, and
8750    the example specializations for the tree_list_freelist.  */
8751 template <typename T>
8752 class freelist
8753 {
8754   /* Return the next object in a chain.  We could just do type
8755      punning, but if we access the object with its underlying type, we
8756      avoid strict-aliasing trouble.  This needs only work between
8757      poison and reinit.  */
8758   static T *&next (T *obj) { return obj->next; }
8759 
8760   /* Return a newly allocated, uninitialized or minimally-initialized
8761      object of type T.  Any initialization performed by anew should
8762      either remain across the life of the object and the execution of
8763      poison, or be redone by reinit.  */
8764   static T *anew () { return ggc_alloc<T> (); }
8765 
8766   /* Optionally scribble all over the bits holding the object, so that
8767      they become (mostly?) uninitialized memory.  This is called while
8768      preparing to make the object part of the free list.  */
8769   static void poison (T *obj) {
8770     T *p ATTRIBUTE_UNUSED = obj;
8771     T **q ATTRIBUTE_UNUSED = &next (obj);
8772 
8773 #ifdef ENABLE_GC_CHECKING
8774     /* Poison the data, to indicate the data is garbage.  */
8775     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
8776     memset (p, 0xa5, sizeof (*p));
8777 #endif
8778     /* Let valgrind know the object is free.  */
8779     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
8780 
8781     /* Let valgrind know the next portion of the object is available,
8782        but uninitialized.  */
8783     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
8784   }
8785 
8786   /* Bring an object that underwent at least one lifecycle after anew
8787      and before the most recent free and poison, back to a usable
8788      state, reinitializing whatever is needed for it to be
8789      functionally equivalent to an object just allocated and returned
8790      by anew.  This may poison or clear the next field, used by
8791      freelist housekeeping after poison was called.  */
8792   static void reinit (T *obj) {
8793     T **q ATTRIBUTE_UNUSED = &next (obj);
8794 
8795 #ifdef ENABLE_GC_CHECKING
8796     memset (q, 0xa5, sizeof (*q));
8797 #endif
8798     /* Let valgrind know the entire object is available, but
8799        uninitialized.  */
8800     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
8801   }
8802 
8803   /* Reference a GTY-deletable pointer that points to the first object
8804      in the free list proper.  */
8805   T *&head;
8806 public:
8807   /* Construct a freelist object chaining objects off of HEAD.  */
8808   freelist (T *&head) : head(head) {}
8809 
8810   /* Add OBJ to the free object list.  The former head becomes OBJ's
8811      successor.  */
8812   void free (T *obj)
8813   {
8814     poison (obj);
8815     next (obj) = head;
8816     head = obj;
8817   }
8818 
8819   /* Take an object from the free list, if one is available, or
8820      allocate a new one.  Objects taken from the free list should be
8821      regarded as filled with garbage, except for bits that are
8822      configured to be preserved across free and alloc.  */
8823   T *alloc ()
8824   {
8825     if (head)
8826       {
8827 	T *obj = head;
8828 	head = next (head);
8829 	reinit (obj);
8830 	return obj;
8831       }
8832     else
8833       return anew ();
8834   }
8835 };
8836 
8837 /* Explicitly specialize the interfaces for freelist<tree_node>: we
8838    want to allocate a TREE_LIST using the usual interface, and ensure
8839    TREE_CHAIN remains functional.  Alas, we have to duplicate a bit of
8840    build_tree_list logic in reinit, so this could go out of sync.  */
8841 template <>
8842 inline tree &
8843 freelist<tree_node>::next (tree obj)
8844 {
8845   return TREE_CHAIN (obj);
8846 }
8847 template <>
8848 inline tree
8849 freelist<tree_node>::anew ()
8850 {
8851   return build_tree_list (NULL, NULL);
8852 }
8853 template <>
8854 inline void
8855 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
8856 {
8857   int size ATTRIBUTE_UNUSED = sizeof (tree_list);
8858   tree p ATTRIBUTE_UNUSED = obj;
8859   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
8860   tree *q ATTRIBUTE_UNUSED = &next (obj);
8861 
8862 #ifdef ENABLE_GC_CHECKING
8863   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
8864 
8865   /* Poison the data, to indicate the data is garbage.  */
8866   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
8867   memset (p, 0xa5, size);
8868 #endif
8869   /* Let valgrind know the object is free.  */
8870   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
8871   /* But we still want to use the TREE_CODE and TREE_CHAIN parts.  */
8872   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8873   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
8874 
8875 #ifdef ENABLE_GC_CHECKING
8876   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
8877   /* Keep TREE_CHAIN functional.  */
8878   TREE_SET_CODE (obj, TREE_LIST);
8879 #else
8880   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8881 #endif
8882 }
8883 template <>
8884 inline void
8885 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
8886 {
8887   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
8888 
8889 #ifdef ENABLE_GC_CHECKING
8890   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
8891   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
8892   memset (obj, 0, sizeof (tree_list));
8893 #endif
8894 
8895   /* Let valgrind know the entire object is available, but
8896      uninitialized.  */
8897   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
8898 
8899 #ifdef ENABLE_GC_CHECKING
8900   TREE_SET_CODE (obj, TREE_LIST);
8901 #else
8902   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8903 #endif
8904 }
8905 
8906 /* Point to the first object in the TREE_LIST freelist.  */
8907 static GTY((deletable)) tree tree_list_freelist_head;
8908 /* Return the/an actual TREE_LIST freelist.  */
8909 static inline freelist<tree_node>
8910 tree_list_freelist ()
8911 {
8912   return tree_list_freelist_head;
8913 }
8914 
8915 /* Point to the first object in the tinst_level freelist.  */
8916 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
8917 /* Return the/an actual tinst_level freelist.  */
8918 static inline freelist<tinst_level>
8919 tinst_level_freelist ()
8920 {
8921   return tinst_level_freelist_head;
8922 }
8923 
8924 /* Point to the first object in the pending_template freelist.  */
8925 static GTY((deletable)) pending_template *pending_template_freelist_head;
8926 /* Return the/an actual pending_template freelist.  */
8927 static inline freelist<pending_template>
8928 pending_template_freelist ()
8929 {
8930   return pending_template_freelist_head;
8931 }
8932 
8933 /* Build the TREE_LIST object out of a split list, store it
8934    permanently, and return it.  */
8935 tree
8936 tinst_level::to_list ()
8937 {
8938   gcc_assert (split_list_p ());
8939   tree ret = tree_list_freelist ().alloc ();
8940   TREE_PURPOSE (ret) = tldcl;
8941   TREE_VALUE (ret) = targs;
8942   tldcl = ret;
8943   targs = NULL;
8944   gcc_assert (tree_list_p ());
8945   return ret;
8946 }
8947 
8948 const unsigned short tinst_level::refcount_infinity;
8949 
8950 /* Increment OBJ's refcount unless it is already infinite.  */
8951 static tinst_level *
8952 inc_refcount_use (tinst_level *obj)
8953 {
8954   if (obj && obj->refcount != tinst_level::refcount_infinity)
8955     ++obj->refcount;
8956   return obj;
8957 }
8958 
8959 /* Release storage for OBJ and node, if it's a TREE_LIST.  */
8960 void
8961 tinst_level::free (tinst_level *obj)
8962 {
8963   if (obj->tree_list_p ())
8964     tree_list_freelist ().free (obj->get_node ());
8965   tinst_level_freelist ().free (obj);
8966 }
8967 
8968 /* Decrement OBJ's refcount if not infinite.  If it reaches zero, release
8969    OBJ's DECL and OBJ, and start over with the tinst_level object that
8970    used to be referenced by OBJ's NEXT.  */
8971 static void
8972 dec_refcount_use (tinst_level *obj)
8973 {
8974   while (obj
8975 	 && obj->refcount != tinst_level::refcount_infinity
8976 	 && !--obj->refcount)
8977     {
8978       tinst_level *next = obj->next;
8979       tinst_level::free (obj);
8980       obj = next;
8981     }
8982 }
8983 
8984 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
8985    and of the former PTR.  Omitting the second argument is equivalent
8986    to passing (T*)NULL; this is allowed because passing the
8987    zero-valued integral constant NULL confuses type deduction and/or
8988    overload resolution.  */
8989 template <typename T>
8990 static void
8991 set_refcount_ptr (T *& ptr, T *obj = NULL)
8992 {
8993   T *save = ptr;
8994   ptr = inc_refcount_use (obj);
8995   dec_refcount_use (save);
8996 }
8997 
8998 static void
8999 add_pending_template (tree d)
9000 {
9001   tree ti = (TYPE_P (d)
9002 	     ? CLASSTYPE_TEMPLATE_INFO (d)
9003 	     : DECL_TEMPLATE_INFO (d));
9004   struct pending_template *pt;
9005   int level;
9006 
9007   if (TI_PENDING_TEMPLATE_FLAG (ti))
9008     return;
9009 
9010   /* We are called both from instantiate_decl, where we've already had a
9011      tinst_level pushed, and instantiate_template, where we haven't.
9012      Compensate.  */
9013   gcc_assert (TREE_CODE (d) != TREE_LIST);
9014   level = !current_tinst_level
9015     || current_tinst_level->maybe_get_node () != d;
9016 
9017   if (level)
9018     push_tinst_level (d);
9019 
9020   pt = pending_template_freelist ().alloc ();
9021   pt->next = NULL;
9022   pt->tinst = NULL;
9023   set_refcount_ptr (pt->tinst, current_tinst_level);
9024   if (last_pending_template)
9025     last_pending_template->next = pt;
9026   else
9027     pending_templates = pt;
9028 
9029   last_pending_template = pt;
9030 
9031   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9032 
9033   if (level)
9034     pop_tinst_level ();
9035 }
9036 
9037 
9038 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9039    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
9040    documentation for TEMPLATE_ID_EXPR.  */
9041 
9042 tree
9043 lookup_template_function (tree fns, tree arglist)
9044 {
9045   tree type;
9046 
9047   if (fns == error_mark_node || arglist == error_mark_node)
9048     return error_mark_node;
9049 
9050   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9051 
9052   if (!is_overloaded_fn (fns) && !identifier_p (fns))
9053     {
9054       error ("%q#D is not a function template", fns);
9055       return error_mark_node;
9056     }
9057 
9058   if (BASELINK_P (fns))
9059     {
9060       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9061 					 unknown_type_node,
9062 					 BASELINK_FUNCTIONS (fns),
9063 					 arglist);
9064       return fns;
9065     }
9066 
9067   type = TREE_TYPE (fns);
9068   if (TREE_CODE (fns) == OVERLOAD || !type)
9069     type = unknown_type_node;
9070 
9071   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
9072 }
9073 
9074 /* Within the scope of a template class S<T>, the name S gets bound
9075    (in build_self_reference) to a TYPE_DECL for the class, not a
9076    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
9077    or one of its enclosing classes, and that type is a template,
9078    return the associated TEMPLATE_DECL.  Otherwise, the original
9079    DECL is returned.
9080 
9081    Also handle the case when DECL is a TREE_LIST of ambiguous
9082    injected-class-names from different bases.  */
9083 
9084 tree
9085 maybe_get_template_decl_from_type_decl (tree decl)
9086 {
9087   if (decl == NULL_TREE)
9088     return decl;
9089 
9090   /* DR 176: A lookup that finds an injected-class-name (10.2
9091      [class.member.lookup]) can result in an ambiguity in certain cases
9092      (for example, if it is found in more than one base class). If all of
9093      the injected-class-names that are found refer to specializations of
9094      the same class template, and if the name is followed by a
9095      template-argument-list, the reference refers to the class template
9096      itself and not a specialization thereof, and is not ambiguous.  */
9097   if (TREE_CODE (decl) == TREE_LIST)
9098     {
9099       tree t, tmpl = NULL_TREE;
9100       for (t = decl; t; t = TREE_CHAIN (t))
9101 	{
9102 	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9103 	  if (!tmpl)
9104 	    tmpl = elt;
9105 	  else if (tmpl != elt)
9106 	    break;
9107 	}
9108       if (tmpl && t == NULL_TREE)
9109 	return tmpl;
9110       else
9111 	return decl;
9112     }
9113 
9114   return (decl != NULL_TREE
9115 	  && DECL_SELF_REFERENCE_P (decl)
9116 	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9117     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9118 }
9119 
9120 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9121    parameters, find the desired type.
9122 
9123    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9124 
9125    IN_DECL, if non-NULL, is the template declaration we are trying to
9126    instantiate.
9127 
9128    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9129    the class we are looking up.
9130 
9131    Issue error and warning messages under control of COMPLAIN.
9132 
9133    If the template class is really a local class in a template
9134    function, then the FUNCTION_CONTEXT is the function in which it is
9135    being instantiated.
9136 
9137    ??? Note that this function is currently called *twice* for each
9138    template-id: the first time from the parser, while creating the
9139    incomplete type (finish_template_type), and the second type during the
9140    real instantiation (instantiate_template_class). This is surely something
9141    that we want to avoid. It also causes some problems with argument
9142    coercion (see convert_nontype_argument for more information on this).  */
9143 
9144 static tree
9145 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9146 			 int entering_scope, tsubst_flags_t complain)
9147 {
9148   tree templ = NULL_TREE, parmlist;
9149   tree t;
9150   spec_entry **slot;
9151   spec_entry *entry;
9152   spec_entry elt;
9153   hashval_t hash;
9154 
9155   if (identifier_p (d1))
9156     {
9157       tree value = innermost_non_namespace_value (d1);
9158       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9159 	templ = value;
9160       else
9161 	{
9162 	  if (context)
9163 	    push_decl_namespace (context);
9164 	  templ = lookup_name (d1);
9165 	  templ = maybe_get_template_decl_from_type_decl (templ);
9166 	  if (context)
9167 	    pop_decl_namespace ();
9168 	}
9169       if (templ)
9170 	context = DECL_CONTEXT (templ);
9171     }
9172   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9173     {
9174       tree type = TREE_TYPE (d1);
9175 
9176       /* If we are declaring a constructor, say A<T>::A<T>, we will get
9177 	 an implicit typename for the second A.  Deal with it.  */
9178       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9179 	type = TREE_TYPE (type);
9180 
9181       if (CLASSTYPE_TEMPLATE_INFO (type))
9182 	{
9183 	  templ = CLASSTYPE_TI_TEMPLATE (type);
9184 	  d1 = DECL_NAME (templ);
9185 	}
9186     }
9187   else if (TREE_CODE (d1) == ENUMERAL_TYPE
9188 	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9189     {
9190       templ = TYPE_TI_TEMPLATE (d1);
9191       d1 = DECL_NAME (templ);
9192     }
9193   else if (DECL_TYPE_TEMPLATE_P (d1))
9194     {
9195       templ = d1;
9196       d1 = DECL_NAME (templ);
9197       context = DECL_CONTEXT (templ);
9198     }
9199   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9200     {
9201       templ = d1;
9202       d1 = DECL_NAME (templ);
9203     }
9204 
9205   /* Issue an error message if we didn't find a template.  */
9206   if (! templ)
9207     {
9208       if (complain & tf_error)
9209 	error ("%qT is not a template", d1);
9210       return error_mark_node;
9211     }
9212 
9213   if (TREE_CODE (templ) != TEMPLATE_DECL
9214 	 /* Make sure it's a user visible template, if it was named by
9215 	    the user.  */
9216       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9217 	  && !PRIMARY_TEMPLATE_P (templ)))
9218     {
9219       if (complain & tf_error)
9220 	{
9221 	  error ("non-template type %qT used as a template", d1);
9222 	  if (in_decl)
9223 	    error ("for template declaration %q+D", in_decl);
9224 	}
9225       return error_mark_node;
9226     }
9227 
9228   complain &= ~tf_user;
9229 
9230   /* An alias that just changes the name of a template is equivalent to the
9231      other template, so if any of the arguments are pack expansions, strip
9232      the alias to avoid problems with a pack expansion passed to a non-pack
9233      alias template parameter (DR 1430).  */
9234   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9235     templ = get_underlying_template (templ);
9236 
9237   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9238     {
9239       tree parm;
9240       tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9241       if (arglist2 == error_mark_node
9242 	  || (!uses_template_parms (arglist2)
9243 	      && check_instantiated_args (templ, arglist2, complain)))
9244 	return error_mark_node;
9245 
9246       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9247       return parm;
9248     }
9249   else
9250     {
9251       tree template_type = TREE_TYPE (templ);
9252       tree gen_tmpl;
9253       tree type_decl;
9254       tree found = NULL_TREE;
9255       int arg_depth;
9256       int parm_depth;
9257       int is_dependent_type;
9258       int use_partial_inst_tmpl = false;
9259 
9260       if (template_type == error_mark_node)
9261 	/* An error occurred while building the template TEMPL, and a
9262 	   diagnostic has most certainly been emitted for that
9263 	   already.  Let's propagate that error.  */
9264 	return error_mark_node;
9265 
9266       gen_tmpl = most_general_template (templ);
9267       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9268       parm_depth = TMPL_PARMS_DEPTH (parmlist);
9269       arg_depth = TMPL_ARGS_DEPTH (arglist);
9270 
9271       if (arg_depth == 1 && parm_depth > 1)
9272 	{
9273 	  /* We've been given an incomplete set of template arguments.
9274 	     For example, given:
9275 
9276 	       template <class T> struct S1 {
9277 		 template <class U> struct S2 {};
9278 		 template <class U> struct S2<U*> {};
9279 		};
9280 
9281 	     we will be called with an ARGLIST of `U*', but the
9282 	     TEMPLATE will be `template <class T> template
9283 	     <class U> struct S1<T>::S2'.  We must fill in the missing
9284 	     arguments.  */
9285 	  tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9286 	  arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9287 	  arg_depth = TMPL_ARGS_DEPTH (arglist);
9288 	}
9289 
9290       /* Now we should have enough arguments.  */
9291       gcc_assert (parm_depth == arg_depth);
9292 
9293       /* From here on, we're only interested in the most general
9294 	 template.  */
9295 
9296       /* Calculate the BOUND_ARGS.  These will be the args that are
9297 	 actually tsubst'd into the definition to create the
9298 	 instantiation.  */
9299       arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
9300 						 complain,
9301 						 /*require_all_args=*/true,
9302 						 /*use_default_args=*/true);
9303 
9304       if (arglist == error_mark_node)
9305 	/* We were unable to bind the arguments.  */
9306 	return error_mark_node;
9307 
9308       /* In the scope of a template class, explicit references to the
9309 	 template class refer to the type of the template, not any
9310 	 instantiation of it.  For example, in:
9311 
9312 	   template <class T> class C { void f(C<T>); }
9313 
9314 	 the `C<T>' is just the same as `C'.  Outside of the
9315 	 class, however, such a reference is an instantiation.  */
9316       if (entering_scope
9317 	  || !PRIMARY_TEMPLATE_P (gen_tmpl)
9318 	  || currently_open_class (template_type))
9319 	{
9320 	  tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9321 
9322 	  if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9323 	    return template_type;
9324 	}
9325 
9326       /* If we already have this specialization, return it.  */
9327       elt.tmpl = gen_tmpl;
9328       elt.args = arglist;
9329       elt.spec = NULL_TREE;
9330       hash = spec_hasher::hash (&elt);
9331       entry = type_specializations->find_with_hash (&elt, hash);
9332 
9333       if (entry)
9334 	return entry->spec;
9335 
9336       /* If the the template's constraints are not satisfied,
9337          then we cannot form a valid type.
9338 
9339          Note that the check is deferred until after the hash
9340          lookup. This prevents redundant checks on previously
9341          instantiated specializations. */
9342       if (flag_concepts && !constraints_satisfied_p (gen_tmpl, arglist))
9343         {
9344           if (complain & tf_error)
9345             {
9346               error ("template constraint failure");
9347               diagnose_constraints (input_location, gen_tmpl, arglist);
9348             }
9349           return error_mark_node;
9350         }
9351 
9352       is_dependent_type = uses_template_parms (arglist);
9353 
9354       /* If the deduced arguments are invalid, then the binding
9355 	 failed.  */
9356       if (!is_dependent_type
9357 	  && check_instantiated_args (gen_tmpl,
9358 				      INNERMOST_TEMPLATE_ARGS (arglist),
9359 				      complain))
9360 	return error_mark_node;
9361 
9362       if (!is_dependent_type
9363 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
9364 	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9365 	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9366 	{
9367 	  found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
9368 				      DECL_NAME (gen_tmpl),
9369 				      /*tag_scope=*/ts_global);
9370 	  return found;
9371 	}
9372 
9373       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
9374 			complain, in_decl);
9375       if (context == error_mark_node)
9376 	return error_mark_node;
9377 
9378       if (!context)
9379 	context = global_namespace;
9380 
9381       /* Create the type.  */
9382       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9383 	{
9384 	  /* The user referred to a specialization of an alias
9385 	    template represented by GEN_TMPL.
9386 
9387 	    [temp.alias]/2 says:
9388 
9389 	        When a template-id refers to the specialization of an
9390 		alias template, it is equivalent to the associated
9391 		type obtained by substitution of its
9392 		template-arguments for the template-parameters in the
9393 		type-id of the alias template.  */
9394 
9395 	  t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
9396 	  /* Note that the call above (by indirectly calling
9397 	     register_specialization in tsubst_decl) registers the
9398 	     TYPE_DECL representing the specialization of the alias
9399 	     template.  So next time someone substitutes ARGLIST for
9400 	     the template parms into the alias template (GEN_TMPL),
9401 	     she'll get that TYPE_DECL back.  */
9402 
9403 	  if (t == error_mark_node)
9404 	    return t;
9405 	}
9406       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
9407 	{
9408 	  if (!is_dependent_type)
9409 	    {
9410 	      set_current_access_from_decl (TYPE_NAME (template_type));
9411 	      t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
9412 			      tsubst (ENUM_UNDERLYING_TYPE (template_type),
9413 				      arglist, complain, in_decl),
9414 			      tsubst_attributes (TYPE_ATTRIBUTES (template_type),
9415 						 arglist, complain, in_decl),
9416 			      SCOPED_ENUM_P (template_type), NULL);
9417 
9418 	      if (t == error_mark_node)
9419 		return t;
9420 	    }
9421 	  else
9422             {
9423               /* We don't want to call start_enum for this type, since
9424                  the values for the enumeration constants may involve
9425                  template parameters.  And, no one should be interested
9426                  in the enumeration constants for such a type.  */
9427               t = cxx_make_type (ENUMERAL_TYPE);
9428               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
9429             }
9430           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
9431 	  ENUM_FIXED_UNDERLYING_TYPE_P (t)
9432 	    = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
9433 	}
9434       else if (CLASS_TYPE_P (template_type))
9435 	{
9436 	  /* Lambda closures are regenerated in tsubst_lambda_expr, not
9437 	     instantiated here.  */
9438 	  gcc_assert (!LAMBDA_TYPE_P (template_type));
9439 
9440 	  t = make_class_type (TREE_CODE (template_type));
9441 	  CLASSTYPE_DECLARED_CLASS (t)
9442 	    = CLASSTYPE_DECLARED_CLASS (template_type);
9443 	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
9444 
9445 	  /* A local class.  Make sure the decl gets registered properly.  */
9446 	  if (context == current_function_decl)
9447 	    if (pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current)
9448 		== error_mark_node)
9449 	      return error_mark_node;
9450 
9451 	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
9452 	    /* This instantiation is another name for the primary
9453 	       template type. Set the TYPE_CANONICAL field
9454 	       appropriately. */
9455 	    TYPE_CANONICAL (t) = template_type;
9456 	  else if (any_template_arguments_need_structural_equality_p (arglist))
9457 	    /* Some of the template arguments require structural
9458 	       equality testing, so this template class requires
9459 	       structural equality testing. */
9460 	    SET_TYPE_STRUCTURAL_EQUALITY (t);
9461 	}
9462       else
9463 	gcc_unreachable ();
9464 
9465       /* If we called start_enum or pushtag above, this information
9466 	 will already be set up.  */
9467       if (!TYPE_NAME (t))
9468 	{
9469 	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
9470 
9471 	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
9472 	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
9473 	  DECL_SOURCE_LOCATION (type_decl)
9474 	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
9475 	}
9476       else
9477 	type_decl = TYPE_NAME (t);
9478 
9479       if (CLASS_TYPE_P (template_type))
9480 	{
9481 	  TREE_PRIVATE (type_decl)
9482 	    = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
9483 	  TREE_PROTECTED (type_decl)
9484 	    = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
9485 	  if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
9486 	    {
9487 	      DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
9488 	      DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
9489 	    }
9490 	}
9491 
9492       if (OVERLOAD_TYPE_P (t)
9493 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9494 	{
9495 	  static const char *tags[] = {"abi_tag", "may_alias"};
9496 
9497 	  for (unsigned ix = 0; ix != 2; ix++)
9498 	    {
9499 	      tree attributes
9500 		= lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
9501 
9502 	      if (attributes)
9503 		TYPE_ATTRIBUTES (t)
9504 		  = tree_cons (TREE_PURPOSE (attributes),
9505 			       TREE_VALUE (attributes),
9506 			       TYPE_ATTRIBUTES (t));
9507 	    }
9508 	}
9509 
9510       /* Let's consider the explicit specialization of a member
9511          of a class template specialization that is implicitly instantiated,
9512 	 e.g.:
9513 	     template<class T>
9514 	     struct S
9515 	     {
9516 	       template<class U> struct M {}; //#0
9517 	     };
9518 
9519 	     template<>
9520 	     template<>
9521 	     struct S<int>::M<char> //#1
9522 	     {
9523 	       int i;
9524 	     };
9525 	[temp.expl.spec]/4 says this is valid.
9526 
9527 	In this case, when we write:
9528 	S<int>::M<char> m;
9529 
9530 	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
9531 	the one of #0.
9532 
9533 	When we encounter #1, we want to store the partial instantiation
9534 	of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
9535 
9536 	For all cases other than this "explicit specialization of member of a
9537 	class template", we just want to store the most general template into
9538 	the CLASSTYPE_TI_TEMPLATE of M.
9539 
9540 	This case of "explicit specialization of member of a class template"
9541 	only happens when:
9542 	1/ the enclosing class is an instantiation of, and therefore not
9543 	the same as, the context of the most general template, and
9544 	2/ we aren't looking at the partial instantiation itself, i.e.
9545 	the innermost arguments are not the same as the innermost parms of
9546 	the most general template.
9547 
9548 	So it's only when 1/ and 2/ happens that we want to use the partial
9549 	instantiation of the member template in lieu of its most general
9550 	template.  */
9551 
9552       if (PRIMARY_TEMPLATE_P (gen_tmpl)
9553 	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
9554 	  /* the enclosing class must be an instantiation...  */
9555 	  && CLASS_TYPE_P (context)
9556 	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
9557 	{
9558 	  TREE_VEC_LENGTH (arglist)--;
9559 	  ++processing_template_decl;
9560 	  tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
9561 	  tree partial_inst_args =
9562 	    tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
9563 		    arglist, complain, NULL_TREE);
9564 	  --processing_template_decl;
9565 	  TREE_VEC_LENGTH (arglist)++;
9566 	  if (partial_inst_args == error_mark_node)
9567 	    return error_mark_node;
9568 	  use_partial_inst_tmpl =
9569 	    /*...and we must not be looking at the partial instantiation
9570 	     itself. */
9571 	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
9572 				 partial_inst_args);
9573 	}
9574 
9575       if (!use_partial_inst_tmpl)
9576 	/* This case is easy; there are no member templates involved.  */
9577 	found = gen_tmpl;
9578       else
9579 	{
9580 	  /* This is a full instantiation of a member template.  Find
9581 	     the partial instantiation of which this is an instance.  */
9582 
9583 	  /* Temporarily reduce by one the number of levels in the ARGLIST
9584 	     so as to avoid comparing the last set of arguments.  */
9585 	  TREE_VEC_LENGTH (arglist)--;
9586 	  found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
9587 	  TREE_VEC_LENGTH (arglist)++;
9588 	  /* FOUND is either a proper class type, or an alias
9589 	     template specialization.  In the later case, it's a
9590 	     TYPE_DECL, resulting from the substituting of arguments
9591 	     for parameters in the TYPE_DECL of the alias template
9592 	     done earlier.  So be careful while getting the template
9593 	     of FOUND.  */
9594 	  found = (TREE_CODE (found) == TEMPLATE_DECL
9595 		   ? found
9596 		   : (TREE_CODE (found) == TYPE_DECL
9597 		      ? DECL_TI_TEMPLATE (found)
9598 		      : CLASSTYPE_TI_TEMPLATE (found)));
9599 	}
9600 
9601       // Build template info for the new specialization.
9602       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
9603 
9604       elt.spec = t;
9605       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
9606       entry = ggc_alloc<spec_entry> ();
9607       *entry = elt;
9608       *slot = entry;
9609 
9610       /* Note this use of the partial instantiation so we can check it
9611 	 later in maybe_process_partial_specialization.  */
9612       DECL_TEMPLATE_INSTANTIATIONS (found)
9613 	= tree_cons (arglist, t,
9614 		     DECL_TEMPLATE_INSTANTIATIONS (found));
9615 
9616       if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
9617 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9618 	/* Now that the type has been registered on the instantiations
9619 	   list, we set up the enumerators.  Because the enumeration
9620 	   constants may involve the enumeration type itself, we make
9621 	   sure to register the type first, and then create the
9622 	   constants.  That way, doing tsubst_expr for the enumeration
9623 	   constants won't result in recursive calls here; we'll find
9624 	   the instantiation and exit above.  */
9625 	tsubst_enum (template_type, t, arglist);
9626 
9627       if (CLASS_TYPE_P (template_type) && is_dependent_type)
9628 	/* If the type makes use of template parameters, the
9629 	   code that generates debugging information will crash.  */
9630 	DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
9631 
9632       /* Possibly limit visibility based on template args.  */
9633       TREE_PUBLIC (type_decl) = 1;
9634       determine_visibility (type_decl);
9635 
9636       inherit_targ_abi_tags (t);
9637 
9638       return t;
9639     }
9640 }
9641 
9642 /* Wrapper for lookup_template_class_1.  */
9643 
9644 tree
9645 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9646                        int entering_scope, tsubst_flags_t complain)
9647 {
9648   tree ret;
9649   timevar_push (TV_TEMPLATE_INST);
9650   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
9651                                  entering_scope, complain);
9652   timevar_pop (TV_TEMPLATE_INST);
9653   return ret;
9654 }
9655 
9656 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
9657 
9658 tree
9659 lookup_template_variable (tree templ, tree arglist)
9660 {
9661   /* The type of the expression is NULL_TREE since the template-id could refer
9662      to an explicit or partial specialization. */
9663   tree type = NULL_TREE;
9664   if (flag_concepts && variable_concept_p (templ))
9665     /* Except that concepts are always bool.  */
9666     type = boolean_type_node;
9667   return build2 (TEMPLATE_ID_EXPR, type, templ, arglist);
9668 }
9669 
9670 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
9671 
9672 tree
9673 finish_template_variable (tree var, tsubst_flags_t complain)
9674 {
9675   tree templ = TREE_OPERAND (var, 0);
9676   tree arglist = TREE_OPERAND (var, 1);
9677 
9678   /* We never want to return a VAR_DECL for a variable concept, since they
9679      aren't instantiated.  In a template, leave the TEMPLATE_ID_EXPR alone.  */
9680   bool concept_p = flag_concepts && variable_concept_p (templ);
9681   if (concept_p && processing_template_decl)
9682     return var;
9683 
9684   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
9685   arglist = add_outermost_template_args (tmpl_args, arglist);
9686 
9687   templ = most_general_template (templ);
9688   tree parms = DECL_TEMPLATE_PARMS (templ);
9689   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
9690 					     /*req_all*/true,
9691 					     /*use_default*/true);
9692 
9693   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
9694     {
9695       if (complain & tf_error)
9696 	{
9697 	  error ("use of invalid variable template %qE", var);
9698 	  diagnose_constraints (location_of (var), templ, arglist);
9699 	}
9700       return error_mark_node;
9701     }
9702 
9703   /* If a template-id refers to a specialization of a variable
9704      concept, then the expression is true if and only if the
9705      concept's constraints are satisfied by the given template
9706      arguments.
9707 
9708      NOTE: This is an extension of Concepts Lite TS that
9709      allows constraints to be used in expressions. */
9710   if (concept_p)
9711     {
9712       tree decl = DECL_TEMPLATE_RESULT (templ);
9713       return evaluate_variable_concept (decl, arglist);
9714     }
9715 
9716   return instantiate_template (templ, arglist, complain);
9717 }
9718 
9719 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
9720    TARGS template args, and instantiate it if it's not dependent.  */
9721 
9722 tree
9723 lookup_and_finish_template_variable (tree templ, tree targs,
9724 				     tsubst_flags_t complain)
9725 {
9726   templ = lookup_template_variable (templ, targs);
9727   if (!any_dependent_template_arguments_p (targs))
9728     {
9729       templ = finish_template_variable (templ, complain);
9730       mark_used (templ);
9731     }
9732 
9733   return convert_from_reference (templ);
9734 }
9735 
9736 
9737 struct pair_fn_data
9738 {
9739   tree_fn_t fn;
9740   tree_fn_t any_fn;
9741   void *data;
9742   /* True when we should also visit template parameters that occur in
9743      non-deduced contexts.  */
9744   bool include_nondeduced_p;
9745   hash_set<tree> *visited;
9746 };
9747 
9748 /* Called from for_each_template_parm via walk_tree.  */
9749 
9750 static tree
9751 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
9752 {
9753   tree t = *tp;
9754   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
9755   tree_fn_t fn = pfd->fn;
9756   void *data = pfd->data;
9757   tree result = NULL_TREE;
9758 
9759 #define WALK_SUBTREE(NODE)						\
9760   do									\
9761     {									\
9762       result = for_each_template_parm (NODE, fn, data, pfd->visited,	\
9763 				       pfd->include_nondeduced_p,	\
9764 				       pfd->any_fn);			\
9765       if (result) goto out;						\
9766     }									\
9767   while (0)
9768 
9769   if (pfd->any_fn && (*pfd->any_fn)(t, data))
9770     return t;
9771 
9772   if (TYPE_P (t)
9773       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
9774     WALK_SUBTREE (TYPE_CONTEXT (t));
9775 
9776   switch (TREE_CODE (t))
9777     {
9778     case RECORD_TYPE:
9779       if (TYPE_PTRMEMFUNC_P (t))
9780 	break;
9781       /* Fall through.  */
9782 
9783     case UNION_TYPE:
9784     case ENUMERAL_TYPE:
9785       if (!TYPE_TEMPLATE_INFO (t))
9786 	*walk_subtrees = 0;
9787       else
9788 	WALK_SUBTREE (TYPE_TI_ARGS (t));
9789       break;
9790 
9791     case INTEGER_TYPE:
9792       WALK_SUBTREE (TYPE_MIN_VALUE (t));
9793       WALK_SUBTREE (TYPE_MAX_VALUE (t));
9794       break;
9795 
9796     case METHOD_TYPE:
9797       /* Since we're not going to walk subtrees, we have to do this
9798 	 explicitly here.  */
9799       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
9800       /* Fall through.  */
9801 
9802     case FUNCTION_TYPE:
9803       /* Check the return type.  */
9804       WALK_SUBTREE (TREE_TYPE (t));
9805 
9806       /* Check the parameter types.  Since default arguments are not
9807 	 instantiated until they are needed, the TYPE_ARG_TYPES may
9808 	 contain expressions that involve template parameters.  But,
9809 	 no-one should be looking at them yet.  And, once they're
9810 	 instantiated, they don't contain template parameters, so
9811 	 there's no point in looking at them then, either.  */
9812       {
9813 	tree parm;
9814 
9815 	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
9816 	  WALK_SUBTREE (TREE_VALUE (parm));
9817 
9818 	/* Since we've already handled the TYPE_ARG_TYPES, we don't
9819 	   want walk_tree walking into them itself.  */
9820 	*walk_subtrees = 0;
9821       }
9822 
9823       if (flag_noexcept_type)
9824 	{
9825 	  tree spec = TYPE_RAISES_EXCEPTIONS (t);
9826 	  if (spec)
9827 	    WALK_SUBTREE (TREE_PURPOSE (spec));
9828 	}
9829       break;
9830 
9831     case TYPEOF_TYPE:
9832     case UNDERLYING_TYPE:
9833       if (pfd->include_nondeduced_p
9834 	  && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
9835 				     pfd->visited,
9836 				     pfd->include_nondeduced_p,
9837 				     pfd->any_fn))
9838 	return error_mark_node;
9839       break;
9840 
9841     case FUNCTION_DECL:
9842     case VAR_DECL:
9843       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9844 	WALK_SUBTREE (DECL_TI_ARGS (t));
9845       /* Fall through.  */
9846 
9847     case PARM_DECL:
9848     case CONST_DECL:
9849       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
9850 	WALK_SUBTREE (DECL_INITIAL (t));
9851       if (DECL_CONTEXT (t)
9852 	  && pfd->include_nondeduced_p)
9853 	WALK_SUBTREE (DECL_CONTEXT (t));
9854       break;
9855 
9856     case BOUND_TEMPLATE_TEMPLATE_PARM:
9857       /* Record template parameters such as `T' inside `TT<T>'.  */
9858       WALK_SUBTREE (TYPE_TI_ARGS (t));
9859       /* Fall through.  */
9860 
9861     case TEMPLATE_TEMPLATE_PARM:
9862     case TEMPLATE_TYPE_PARM:
9863     case TEMPLATE_PARM_INDEX:
9864       if (fn && (*fn)(t, data))
9865 	return t;
9866       else if (!fn)
9867 	return t;
9868       break;
9869 
9870     case TEMPLATE_DECL:
9871       /* A template template parameter is encountered.  */
9872       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9873 	WALK_SUBTREE (TREE_TYPE (t));
9874 
9875       /* Already substituted template template parameter */
9876       *walk_subtrees = 0;
9877       break;
9878 
9879     case TYPENAME_TYPE:
9880       /* A template-id in a TYPENAME_TYPE might be a deduced context after
9881 	 partial instantiation.  */
9882       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
9883       break;
9884 
9885     case CONSTRUCTOR:
9886       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
9887 	  && pfd->include_nondeduced_p)
9888 	WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
9889       break;
9890 
9891     case INDIRECT_REF:
9892     case COMPONENT_REF:
9893       /* If there's no type, then this thing must be some expression
9894 	 involving template parameters.  */
9895       if (!fn && !TREE_TYPE (t))
9896 	return error_mark_node;
9897       break;
9898 
9899     case MODOP_EXPR:
9900     case CAST_EXPR:
9901     case IMPLICIT_CONV_EXPR:
9902     case REINTERPRET_CAST_EXPR:
9903     case CONST_CAST_EXPR:
9904     case STATIC_CAST_EXPR:
9905     case DYNAMIC_CAST_EXPR:
9906     case ARROW_EXPR:
9907     case DOTSTAR_EXPR:
9908     case TYPEID_EXPR:
9909     case PSEUDO_DTOR_EXPR:
9910       if (!fn)
9911 	return error_mark_node;
9912       break;
9913 
9914     default:
9915       break;
9916     }
9917 
9918   #undef WALK_SUBTREE
9919 
9920   /* We didn't find any template parameters we liked.  */
9921  out:
9922   return result;
9923 }
9924 
9925 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
9926    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
9927    call FN with the parameter and the DATA.
9928    If FN returns nonzero, the iteration is terminated, and
9929    for_each_template_parm returns 1.  Otherwise, the iteration
9930    continues.  If FN never returns a nonzero value, the value
9931    returned by for_each_template_parm is 0.  If FN is NULL, it is
9932    considered to be the function which always returns 1.
9933 
9934    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
9935    parameters that occur in non-deduced contexts.  When false, only
9936    visits those template parameters that can be deduced.  */
9937 
9938 static tree
9939 for_each_template_parm (tree t, tree_fn_t fn, void* data,
9940 			hash_set<tree> *visited,
9941 			bool include_nondeduced_p,
9942 			tree_fn_t any_fn)
9943 {
9944   struct pair_fn_data pfd;
9945   tree result;
9946 
9947   /* Set up.  */
9948   pfd.fn = fn;
9949   pfd.any_fn = any_fn;
9950   pfd.data = data;
9951   pfd.include_nondeduced_p = include_nondeduced_p;
9952 
9953   /* Walk the tree.  (Conceptually, we would like to walk without
9954      duplicates, but for_each_template_parm_r recursively calls
9955      for_each_template_parm, so we would need to reorganize a fair
9956      bit to use walk_tree_without_duplicates, so we keep our own
9957      visited list.)  */
9958   if (visited)
9959     pfd.visited = visited;
9960   else
9961     pfd.visited = new hash_set<tree>;
9962   result = cp_walk_tree (&t,
9963 		         for_each_template_parm_r,
9964 		         &pfd,
9965 		         pfd.visited);
9966 
9967   /* Clean up.  */
9968   if (!visited)
9969     {
9970       delete pfd.visited;
9971       pfd.visited = 0;
9972     }
9973 
9974   return result;
9975 }
9976 
9977 /* Returns true if T depends on any template parameter.  */
9978 
9979 int
9980 uses_template_parms (tree t)
9981 {
9982   if (t == NULL_TREE)
9983     return false;
9984 
9985   bool dependent_p;
9986   int saved_processing_template_decl;
9987 
9988   saved_processing_template_decl = processing_template_decl;
9989   if (!saved_processing_template_decl)
9990     processing_template_decl = 1;
9991   if (TYPE_P (t))
9992     dependent_p = dependent_type_p (t);
9993   else if (TREE_CODE (t) == TREE_VEC)
9994     dependent_p = any_dependent_template_arguments_p (t);
9995   else if (TREE_CODE (t) == TREE_LIST)
9996     dependent_p = (uses_template_parms (TREE_VALUE (t))
9997 		   || uses_template_parms (TREE_CHAIN (t)));
9998   else if (TREE_CODE (t) == TYPE_DECL)
9999     dependent_p = dependent_type_p (TREE_TYPE (t));
10000   else if (DECL_P (t)
10001 	   || EXPR_P (t)
10002 	   || TREE_CODE (t) == TEMPLATE_PARM_INDEX
10003 	   || TREE_CODE (t) == OVERLOAD
10004 	   || BASELINK_P (t)
10005 	   || identifier_p (t)
10006 	   || TREE_CODE (t) == TRAIT_EXPR
10007 	   || TREE_CODE (t) == CONSTRUCTOR
10008 	   || CONSTANT_CLASS_P (t))
10009     dependent_p = (type_dependent_expression_p (t)
10010 		   || value_dependent_expression_p (t));
10011   else
10012     {
10013       gcc_assert (t == error_mark_node);
10014       dependent_p = false;
10015     }
10016 
10017   processing_template_decl = saved_processing_template_decl;
10018 
10019   return dependent_p;
10020 }
10021 
10022 /* Returns true iff current_function_decl is an incompletely instantiated
10023    template.  Useful instead of processing_template_decl because the latter
10024    is set to 0 during instantiate_non_dependent_expr.  */
10025 
10026 bool
10027 in_template_function (void)
10028 {
10029   tree fn = current_function_decl;
10030   bool ret;
10031   ++processing_template_decl;
10032   ret = (fn && DECL_LANG_SPECIFIC (fn)
10033 	 && DECL_TEMPLATE_INFO (fn)
10034 	 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10035   --processing_template_decl;
10036   return ret;
10037 }
10038 
10039 /* Returns true if T depends on any template parameter with level LEVEL.  */
10040 
10041 bool
10042 uses_template_parms_level (tree t, int level)
10043 {
10044   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10045 				 /*include_nondeduced_p=*/true);
10046 }
10047 
10048 /* Returns true if the signature of DECL depends on any template parameter from
10049    its enclosing class.  */
10050 
10051 bool
10052 uses_outer_template_parms (tree decl)
10053 {
10054   int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10055   if (depth == 0)
10056     return false;
10057   if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10058 			      &depth, NULL, /*include_nondeduced_p=*/true))
10059     return true;
10060   if (PRIMARY_TEMPLATE_P (decl)
10061       && for_each_template_parm (INNERMOST_TEMPLATE_PARMS
10062 				 (DECL_TEMPLATE_PARMS (decl)),
10063 				 template_parm_outer_level,
10064 				 &depth, NULL, /*include_nondeduced_p=*/true))
10065     return true;
10066   tree ci = get_constraints (decl);
10067   if (ci)
10068     ci = CI_ASSOCIATED_CONSTRAINTS (ci);
10069   if (ci && for_each_template_parm (ci, template_parm_outer_level,
10070 				    &depth, NULL, /*nondeduced*/true))
10071     return true;
10072   return false;
10073 }
10074 
10075 /* Returns TRUE iff INST is an instantiation we don't need to do in an
10076    ill-formed translation unit, i.e. a variable or function that isn't
10077    usable in a constant expression.  */
10078 
10079 static inline bool
10080 neglectable_inst_p (tree d)
10081 {
10082   return (d && DECL_P (d)
10083 	  && !undeduced_auto_decl (d)
10084 	  && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
10085 	       : decl_maybe_constant_var_p (d)));
10086 }
10087 
10088 /* Returns TRUE iff we should refuse to instantiate DECL because it's
10089    neglectable and instantiated from within an erroneous instantiation.  */
10090 
10091 static bool
10092 limit_bad_template_recursion (tree decl)
10093 {
10094   struct tinst_level *lev = current_tinst_level;
10095   int errs = errorcount + sorrycount;
10096   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
10097     return false;
10098 
10099   for (; lev; lev = lev->next)
10100     if (neglectable_inst_p (lev->maybe_get_node ()))
10101       break;
10102 
10103   return (lev && errs > lev->errors);
10104 }
10105 
10106 static int tinst_depth;
10107 extern int max_tinst_depth;
10108 int depth_reached;
10109 
10110 static GTY(()) struct tinst_level *last_error_tinst_level;
10111 
10112 /* We're starting to instantiate D; record the template instantiation context
10113    at LOC for diagnostics and to restore it later.  */
10114 
10115 static bool
10116 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
10117 {
10118   struct tinst_level *new_level;
10119 
10120   if (tinst_depth >= max_tinst_depth)
10121     {
10122       /* Tell error.c not to try to instantiate any templates.  */
10123       at_eof = 2;
10124       fatal_error (input_location,
10125 		   "template instantiation depth exceeds maximum of %d"
10126                    " (use -ftemplate-depth= to increase the maximum)",
10127                    max_tinst_depth);
10128       return false;
10129     }
10130 
10131   /* If the current instantiation caused problems, don't let it instantiate
10132      anything else.  Do allow deduction substitution and decls usable in
10133      constant expressions.  */
10134   if (!targs && limit_bad_template_recursion (tldcl))
10135     return false;
10136 
10137   /* When not -quiet, dump template instantiations other than functions, since
10138      announce_function will take care of those.  */
10139   if (!quiet_flag && !targs
10140       && TREE_CODE (tldcl) != TREE_LIST
10141       && TREE_CODE (tldcl) != FUNCTION_DECL)
10142     fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
10143 
10144   new_level = tinst_level_freelist ().alloc ();
10145   new_level->tldcl = tldcl;
10146   new_level->targs = targs;
10147   new_level->locus = loc;
10148   new_level->errors = errorcount + sorrycount;
10149   new_level->next = NULL;
10150   new_level->refcount = 0;
10151   set_refcount_ptr (new_level->next, current_tinst_level);
10152   set_refcount_ptr (current_tinst_level, new_level);
10153 
10154   ++tinst_depth;
10155   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
10156     depth_reached = tinst_depth;
10157 
10158   return true;
10159 }
10160 
10161 /* We're starting substitution of TMPL<ARGS>; record the template
10162    substitution context for diagnostics and to restore it later.  */
10163 
10164 static bool
10165 push_tinst_level (tree tmpl, tree args)
10166 {
10167   return push_tinst_level_loc (tmpl, args, input_location);
10168 }
10169 
10170 /* We're starting to instantiate D; record INPUT_LOCATION and the
10171    template instantiation context for diagnostics and to restore it
10172    later.  */
10173 
10174 bool
10175 push_tinst_level (tree d)
10176 {
10177   return push_tinst_level_loc (d, input_location);
10178 }
10179 
10180 /* Likewise, but record LOC as the program location.  */
10181 
10182 bool
10183 push_tinst_level_loc (tree d, location_t loc)
10184 {
10185   gcc_assert (TREE_CODE (d) != TREE_LIST);
10186   return push_tinst_level_loc (d, NULL, loc);
10187 }
10188 
10189 /* We're done instantiating this template; return to the instantiation
10190    context.  */
10191 
10192 void
10193 pop_tinst_level (void)
10194 {
10195   /* Restore the filename and line number stashed away when we started
10196      this instantiation.  */
10197   input_location = current_tinst_level->locus;
10198   set_refcount_ptr (current_tinst_level, current_tinst_level->next);
10199   --tinst_depth;
10200 }
10201 
10202 /* We're instantiating a deferred template; restore the template
10203    instantiation context in which the instantiation was requested, which
10204    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
10205 
10206 static tree
10207 reopen_tinst_level (struct tinst_level *level)
10208 {
10209   struct tinst_level *t;
10210 
10211   tinst_depth = 0;
10212   for (t = level; t; t = t->next)
10213     ++tinst_depth;
10214 
10215   set_refcount_ptr (current_tinst_level, level);
10216   pop_tinst_level ();
10217   if (current_tinst_level)
10218     current_tinst_level->errors = errorcount+sorrycount;
10219   return level->maybe_get_node ();
10220 }
10221 
10222 /* Returns the TINST_LEVEL which gives the original instantiation
10223    context.  */
10224 
10225 struct tinst_level *
10226 outermost_tinst_level (void)
10227 {
10228   struct tinst_level *level = current_tinst_level;
10229   if (level)
10230     while (level->next)
10231       level = level->next;
10232   return level;
10233 }
10234 
10235 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
10236    vector of template arguments, as for tsubst.
10237 
10238    Returns an appropriate tsubst'd friend declaration.  */
10239 
10240 static tree
10241 tsubst_friend_function (tree decl, tree args)
10242 {
10243   tree new_friend;
10244 
10245   if (TREE_CODE (decl) == FUNCTION_DECL
10246       && DECL_TEMPLATE_INSTANTIATION (decl)
10247       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
10248     /* This was a friend declared with an explicit template
10249        argument list, e.g.:
10250 
10251        friend void f<>(T);
10252 
10253        to indicate that f was a template instantiation, not a new
10254        function declaration.  Now, we have to figure out what
10255        instantiation of what template.  */
10256     {
10257       tree template_id, arglist, fns;
10258       tree new_args;
10259       tree tmpl;
10260       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
10261 
10262       /* Friend functions are looked up in the containing namespace scope.
10263 	 We must enter that scope, to avoid finding member functions of the
10264 	 current class with same name.  */
10265       push_nested_namespace (ns);
10266       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
10267 			 tf_warning_or_error, NULL_TREE,
10268 			 /*integral_constant_expression_p=*/false);
10269       pop_nested_namespace (ns);
10270       arglist = tsubst (DECL_TI_ARGS (decl), args,
10271 			tf_warning_or_error, NULL_TREE);
10272       template_id = lookup_template_function (fns, arglist);
10273 
10274       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10275       tmpl = determine_specialization (template_id, new_friend,
10276 				       &new_args,
10277 				       /*need_member_template=*/0,
10278 				       TREE_VEC_LENGTH (args),
10279 				       tsk_none);
10280       return instantiate_template (tmpl, new_args, tf_error);
10281     }
10282 
10283   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10284 
10285   /* The NEW_FRIEND will look like an instantiation, to the
10286      compiler, but is not an instantiation from the point of view of
10287      the language.  For example, we might have had:
10288 
10289      template <class T> struct S {
10290        template <class U> friend void f(T, U);
10291      };
10292 
10293      Then, in S<int>, template <class U> void f(int, U) is not an
10294      instantiation of anything.  */
10295   if (new_friend == error_mark_node)
10296     return error_mark_node;
10297 
10298   DECL_USE_TEMPLATE (new_friend) = 0;
10299   if (TREE_CODE (decl) == TEMPLATE_DECL)
10300     {
10301       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
10302       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
10303 	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
10304     }
10305 
10306   /* The mangled name for the NEW_FRIEND is incorrect.  The function
10307      is not a template instantiation and should not be mangled like
10308      one.  Therefore, we forget the mangling here; we'll recompute it
10309      later if we need it.  */
10310   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
10311     {
10312       SET_DECL_RTL (new_friend, NULL);
10313       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
10314     }
10315 
10316   if (DECL_NAMESPACE_SCOPE_P (new_friend))
10317     {
10318       tree old_decl;
10319       tree new_friend_template_info;
10320       tree new_friend_result_template_info;
10321       tree ns;
10322       int  new_friend_is_defn;
10323 
10324       /* We must save some information from NEW_FRIEND before calling
10325 	 duplicate decls since that function will free NEW_FRIEND if
10326 	 possible.  */
10327       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
10328       new_friend_is_defn =
10329 	    (DECL_INITIAL (DECL_TEMPLATE_RESULT
10330 			   (template_for_substitution (new_friend)))
10331 	     != NULL_TREE);
10332       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
10333 	{
10334 	  /* This declaration is a `primary' template.  */
10335 	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
10336 
10337 	  new_friend_result_template_info
10338 	    = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
10339 	}
10340       else
10341 	new_friend_result_template_info = NULL_TREE;
10342 
10343       /* Inside pushdecl_namespace_level, we will push into the
10344 	 current namespace. However, the friend function should go
10345 	 into the namespace of the template.  */
10346       ns = decl_namespace_context (new_friend);
10347       push_nested_namespace (ns);
10348       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
10349       pop_nested_namespace (ns);
10350 
10351       if (old_decl == error_mark_node)
10352 	return error_mark_node;
10353 
10354       if (old_decl != new_friend)
10355 	{
10356 	  /* This new friend declaration matched an existing
10357 	     declaration.  For example, given:
10358 
10359 	       template <class T> void f(T);
10360 	       template <class U> class C {
10361 		 template <class T> friend void f(T) {}
10362 	       };
10363 
10364 	     the friend declaration actually provides the definition
10365 	     of `f', once C has been instantiated for some type.  So,
10366 	     old_decl will be the out-of-class template declaration,
10367 	     while new_friend is the in-class definition.
10368 
10369 	     But, if `f' was called before this point, the
10370 	     instantiation of `f' will have DECL_TI_ARGS corresponding
10371 	     to `T' but not to `U', references to which might appear
10372 	     in the definition of `f'.  Previously, the most general
10373 	     template for an instantiation of `f' was the out-of-class
10374 	     version; now it is the in-class version.  Therefore, we
10375 	     run through all specialization of `f', adding to their
10376 	     DECL_TI_ARGS appropriately.  In particular, they need a
10377 	     new set of outer arguments, corresponding to the
10378 	     arguments for this class instantiation.
10379 
10380 	     The same situation can arise with something like this:
10381 
10382 	       friend void f(int);
10383 	       template <class T> class C {
10384 		 friend void f(T) {}
10385 	       };
10386 
10387 	     when `C<int>' is instantiated.  Now, `f(int)' is defined
10388 	     in the class.  */
10389 
10390 	  if (!new_friend_is_defn)
10391 	    /* On the other hand, if the in-class declaration does
10392 	       *not* provide a definition, then we don't want to alter
10393 	       existing definitions.  We can just leave everything
10394 	       alone.  */
10395 	    ;
10396 	  else
10397 	    {
10398 	      tree new_template = TI_TEMPLATE (new_friend_template_info);
10399 	      tree new_args = TI_ARGS (new_friend_template_info);
10400 
10401 	      /* Overwrite whatever template info was there before, if
10402 		 any, with the new template information pertaining to
10403 		 the declaration.  */
10404 	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
10405 
10406 	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
10407 		{
10408 		  /* We should have called reregister_specialization in
10409 		     duplicate_decls.  */
10410 		  gcc_assert (retrieve_specialization (new_template,
10411 						       new_args, 0)
10412 			      == old_decl);
10413 
10414 		  /* Instantiate it if the global has already been used.  */
10415 		  if (DECL_ODR_USED (old_decl))
10416 		    instantiate_decl (old_decl, /*defer_ok=*/true,
10417 				      /*expl_inst_class_mem_p=*/false);
10418 		}
10419 	      else
10420 		{
10421 		  tree t;
10422 
10423 		  /* Indicate that the old function template is a partial
10424 		     instantiation.  */
10425 		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
10426 		    = new_friend_result_template_info;
10427 
10428 		  gcc_assert (new_template
10429 			      == most_general_template (new_template));
10430 		  gcc_assert (new_template != old_decl);
10431 
10432 		  /* Reassign any specializations already in the hash table
10433 		     to the new more general template, and add the
10434 		     additional template args.  */
10435 		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
10436 		       t != NULL_TREE;
10437 		       t = TREE_CHAIN (t))
10438 		    {
10439 		      tree spec = TREE_VALUE (t);
10440 		      spec_entry elt;
10441 
10442 		      elt.tmpl = old_decl;
10443 		      elt.args = DECL_TI_ARGS (spec);
10444 		      elt.spec = NULL_TREE;
10445 
10446 		      decl_specializations->remove_elt (&elt);
10447 
10448 		      DECL_TI_ARGS (spec)
10449 			= add_outermost_template_args (new_args,
10450 						       DECL_TI_ARGS (spec));
10451 
10452 		      register_specialization
10453 			(spec, new_template, DECL_TI_ARGS (spec), true, 0);
10454 
10455 		    }
10456 		  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
10457 		}
10458 	    }
10459 
10460 	  /* The information from NEW_FRIEND has been merged into OLD_DECL
10461 	     by duplicate_decls.  */
10462 	  new_friend = old_decl;
10463 	}
10464     }
10465   else
10466     {
10467       tree context = DECL_CONTEXT (new_friend);
10468       bool dependent_p;
10469 
10470       /* In the code
10471 	   template <class T> class C {
10472 	     template <class U> friend void C1<U>::f (); // case 1
10473 	     friend void C2<T>::f ();			 // case 2
10474 	   };
10475 	 we only need to make sure CONTEXT is a complete type for
10476 	 case 2.  To distinguish between the two cases, we note that
10477 	 CONTEXT of case 1 remains dependent type after tsubst while
10478 	 this isn't true for case 2.  */
10479       ++processing_template_decl;
10480       dependent_p = dependent_type_p (context);
10481       --processing_template_decl;
10482 
10483       if (!dependent_p
10484 	  && !complete_type_or_else (context, NULL_TREE))
10485 	return error_mark_node;
10486 
10487       if (COMPLETE_TYPE_P (context))
10488 	{
10489 	  tree fn = new_friend;
10490 	  /* do_friend adds the TEMPLATE_DECL for any member friend
10491 	     template even if it isn't a member template, i.e.
10492 	       template <class T> friend A<T>::f();
10493 	     Look through it in that case.  */
10494 	  if (TREE_CODE (fn) == TEMPLATE_DECL
10495 	      && !PRIMARY_TEMPLATE_P (fn))
10496 	    fn = DECL_TEMPLATE_RESULT (fn);
10497 	  /* Check to see that the declaration is really present, and,
10498 	     possibly obtain an improved declaration.  */
10499 	  fn = check_classfn (context, fn, NULL_TREE);
10500 
10501 	  if (fn)
10502 	    new_friend = fn;
10503 	}
10504     }
10505 
10506   return new_friend;
10507 }
10508 
10509 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
10510    template arguments, as for tsubst.
10511 
10512    Returns an appropriate tsubst'd friend type or error_mark_node on
10513    failure.  */
10514 
10515 static tree
10516 tsubst_friend_class (tree friend_tmpl, tree args)
10517 {
10518   tree tmpl;
10519 
10520   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
10521     {
10522       tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
10523       return TREE_TYPE (tmpl);
10524     }
10525 
10526   tree context = CP_DECL_CONTEXT (friend_tmpl);
10527   if (TREE_CODE (context) == NAMESPACE_DECL)
10528     push_nested_namespace (context);
10529   else
10530     push_nested_class (context);
10531 
10532   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), /*prefer_type=*/false,
10533 			   /*non_class=*/false, /*block_p=*/false,
10534 			   /*namespaces_only=*/false, LOOKUP_HIDDEN);
10535 
10536   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
10537     {
10538       /* The friend template has already been declared.  Just
10539 	 check to see that the declarations match, and install any new
10540 	 default parameters.  We must tsubst the default parameters,
10541 	 of course.  We only need the innermost template parameters
10542 	 because that is all that redeclare_class_template will look
10543 	 at.  */
10544       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
10545 	  > TMPL_ARGS_DEPTH (args))
10546 	{
10547 	  tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
10548 					      args, tf_warning_or_error);
10549           location_t saved_input_location = input_location;
10550           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
10551           tree cons = get_constraints (tmpl);
10552           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
10553           input_location = saved_input_location;
10554 	}
10555     }
10556   else
10557     {
10558       /* The friend template has not already been declared.  In this
10559 	 case, the instantiation of the template class will cause the
10560 	 injection of this template into the namespace scope.  */
10561       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
10562 
10563       if (tmpl != error_mark_node)
10564 	{
10565 	  /* The new TMPL is not an instantiation of anything, so we
10566 	     forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE
10567 	     for the new type because that is supposed to be the
10568 	     corresponding template decl, i.e., TMPL.  */
10569 	  DECL_USE_TEMPLATE (tmpl) = 0;
10570 	  DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
10571 	  CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
10572 	  CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
10573 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
10574 
10575 	  /* It is hidden.  */
10576 	  retrofit_lang_decl (DECL_TEMPLATE_RESULT (tmpl));
10577 	  DECL_ANTICIPATED (tmpl)
10578 	    = DECL_ANTICIPATED (DECL_TEMPLATE_RESULT (tmpl)) = true;
10579 
10580 	  /* Inject this template into the enclosing namspace scope.  */
10581 	  tmpl = pushdecl_namespace_level (tmpl, true);
10582 	}
10583     }
10584 
10585   if (TREE_CODE (context) == NAMESPACE_DECL)
10586     pop_nested_namespace (context);
10587   else
10588     pop_nested_class ();
10589 
10590   return TREE_TYPE (tmpl);
10591 }
10592 
10593 /* Returns zero if TYPE cannot be completed later due to circularity.
10594    Otherwise returns one.  */
10595 
10596 static int
10597 can_complete_type_without_circularity (tree type)
10598 {
10599   if (type == NULL_TREE || type == error_mark_node)
10600     return 0;
10601   else if (COMPLETE_TYPE_P (type))
10602     return 1;
10603   else if (TREE_CODE (type) == ARRAY_TYPE)
10604     return can_complete_type_without_circularity (TREE_TYPE (type));
10605   else if (CLASS_TYPE_P (type)
10606 	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
10607     return 0;
10608   else
10609     return 1;
10610 }
10611 
10612 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
10613 				tsubst_flags_t, tree);
10614 
10615 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
10616    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
10617 
10618 static tree
10619 tsubst_attribute (tree t, tree *decl_p, tree args,
10620 		  tsubst_flags_t complain, tree in_decl)
10621 {
10622   gcc_assert (ATTR_IS_DEPENDENT (t));
10623 
10624   tree val = TREE_VALUE (t);
10625   if (val == NULL_TREE)
10626     /* Nothing to do.  */;
10627   else if ((flag_openmp || flag_openmp_simd)
10628 	   && is_attribute_p ("omp declare simd",
10629 			      get_attribute_name (t)))
10630     {
10631       tree clauses = TREE_VALUE (val);
10632       clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
10633 				    complain, in_decl);
10634       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
10635       clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
10636       tree parms = DECL_ARGUMENTS (*decl_p);
10637       clauses
10638 	= c_omp_declare_simd_clauses_to_numbers (parms, clauses);
10639       if (clauses)
10640 	val = build_tree_list (NULL_TREE, clauses);
10641       else
10642 	val = NULL_TREE;
10643     }
10644   /* If the first attribute argument is an identifier, don't
10645      pass it through tsubst.  Attributes like mode, format,
10646      cleanup and several target specific attributes expect it
10647      unmodified.  */
10648   else if (attribute_takes_identifier_p (get_attribute_name (t)))
10649     {
10650       tree chain
10651 	= tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
10652 		       /*integral_constant_expression_p=*/false);
10653       if (chain != TREE_CHAIN (val))
10654 	val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
10655     }
10656   else if (PACK_EXPANSION_P (val))
10657     {
10658       /* An attribute pack expansion.  */
10659       tree purp = TREE_PURPOSE (t);
10660       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
10661       if (pack == error_mark_node)
10662 	return error_mark_node;
10663       int len = TREE_VEC_LENGTH (pack);
10664       tree list = NULL_TREE;
10665       tree *q = &list;
10666       for (int i = 0; i < len; ++i)
10667 	{
10668 	  tree elt = TREE_VEC_ELT (pack, i);
10669 	  *q = build_tree_list (purp, elt);
10670 	  q = &TREE_CHAIN (*q);
10671 	}
10672       return list;
10673     }
10674   else
10675     val = tsubst_expr (val, args, complain, in_decl,
10676 		       /*integral_constant_expression_p=*/false);
10677 
10678   if (val != TREE_VALUE (t))
10679     return build_tree_list (TREE_PURPOSE (t), val);
10680   return t;
10681 }
10682 
10683 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
10684    unchanged or a new TREE_LIST chain.  */
10685 
10686 static tree
10687 tsubst_attributes (tree attributes, tree args,
10688 		   tsubst_flags_t complain, tree in_decl)
10689 {
10690   tree last_dep = NULL_TREE;
10691 
10692   for (tree t = attributes; t; t = TREE_CHAIN (t))
10693     if (ATTR_IS_DEPENDENT (t))
10694       {
10695 	last_dep = t;
10696 	attributes = copy_list (attributes);
10697 	break;
10698       }
10699 
10700   if (last_dep)
10701     for (tree *p = &attributes; *p; )
10702       {
10703 	tree t = *p;
10704 	if (ATTR_IS_DEPENDENT (t))
10705 	  {
10706 	    tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
10707 	    if (subst != t)
10708 	      {
10709 		*p = subst;
10710 		while (*p)
10711 		  p = &TREE_CHAIN (*p);
10712 		*p = TREE_CHAIN (t);
10713 		continue;
10714 	      }
10715 	  }
10716 	p = &TREE_CHAIN (*p);
10717       }
10718 
10719   return attributes;
10720 }
10721 
10722 /* Apply any attributes which had to be deferred until instantiation
10723    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
10724    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
10725 
10726 static void
10727 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
10728 				tree args, tsubst_flags_t complain, tree in_decl)
10729 {
10730   tree last_dep = NULL_TREE;
10731   tree t;
10732   tree *p;
10733 
10734   if (attributes == NULL_TREE)
10735     return;
10736 
10737   if (DECL_P (*decl_p))
10738     {
10739       if (TREE_TYPE (*decl_p) == error_mark_node)
10740 	return;
10741       p = &DECL_ATTRIBUTES (*decl_p);
10742       /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
10743          to our attributes parameter.  */
10744       gcc_assert (*p == attributes);
10745     }
10746   else
10747     {
10748       p = &TYPE_ATTRIBUTES (*decl_p);
10749       /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
10750 	 lookup_template_class_1, and should be preserved.  */
10751       gcc_assert (*p != attributes);
10752       while (*p)
10753 	p = &TREE_CHAIN (*p);
10754     }
10755 
10756   for (t = attributes; t; t = TREE_CHAIN (t))
10757     if (ATTR_IS_DEPENDENT (t))
10758       {
10759 	last_dep = t;
10760 	attributes = copy_list (attributes);
10761 	break;
10762       }
10763 
10764   *p = attributes;
10765   if (last_dep)
10766     {
10767       tree late_attrs = NULL_TREE;
10768       tree *q = &late_attrs;
10769 
10770       for (; *p; )
10771 	{
10772 	  t = *p;
10773 	  if (ATTR_IS_DEPENDENT (t))
10774 	    {
10775 	      *p = TREE_CHAIN (t);
10776 	      TREE_CHAIN (t) = NULL_TREE;
10777 	      *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
10778 	      while (*q)
10779 		q = &TREE_CHAIN (*q);
10780 	    }
10781 	  else
10782 	    p = &TREE_CHAIN (t);
10783 	}
10784 
10785       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
10786     }
10787 }
10788 
10789 /* Perform (or defer) access check for typedefs that were referenced
10790    from within the template TMPL code.
10791    This is a subroutine of instantiate_decl and instantiate_class_template.
10792    TMPL is the template to consider and TARGS is the list of arguments of
10793    that template.  */
10794 
10795 static void
10796 perform_typedefs_access_check (tree tmpl, tree targs)
10797 {
10798   location_t saved_location;
10799   unsigned i;
10800   qualified_typedef_usage_t *iter;
10801 
10802   if (!tmpl
10803       || (!CLASS_TYPE_P (tmpl)
10804 	  && TREE_CODE (tmpl) != FUNCTION_DECL))
10805     return;
10806 
10807   saved_location = input_location;
10808   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
10809     {
10810       tree type_decl = iter->typedef_decl;
10811       tree type_scope = iter->context;
10812 
10813       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
10814 	continue;
10815 
10816       if (uses_template_parms (type_decl))
10817 	type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
10818       if (uses_template_parms (type_scope))
10819 	type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
10820 
10821       /* Make access check error messages point to the location
10822          of the use of the typedef.  */
10823       input_location = iter->locus;
10824       perform_or_defer_access_check (TYPE_BINFO (type_scope),
10825 				     type_decl, type_decl,
10826 				     tf_warning_or_error);
10827     }
10828     input_location = saved_location;
10829 }
10830 
10831 static tree
10832 instantiate_class_template_1 (tree type)
10833 {
10834   tree templ, args, pattern, t, member;
10835   tree typedecl;
10836   tree pbinfo;
10837   tree base_list;
10838   unsigned int saved_maximum_field_alignment;
10839   tree fn_context;
10840 
10841   if (type == error_mark_node)
10842     return error_mark_node;
10843 
10844   if (COMPLETE_OR_OPEN_TYPE_P (type)
10845       || uses_template_parms (type))
10846     return type;
10847 
10848   /* Figure out which template is being instantiated.  */
10849   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
10850   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
10851 
10852   /* Mark the type as in the process of being defined.  */
10853   TYPE_BEING_DEFINED (type) = 1;
10854 
10855   /* Determine what specialization of the original template to
10856      instantiate.  */
10857   t = most_specialized_partial_spec (type, tf_warning_or_error);
10858   if (t == error_mark_node)
10859     return error_mark_node;
10860   else if (t)
10861     {
10862       /* This TYPE is actually an instantiation of a partial
10863 	 specialization.  We replace the innermost set of ARGS with
10864 	 the arguments appropriate for substitution.  For example,
10865 	 given:
10866 
10867 	   template <class T> struct S {};
10868 	   template <class T> struct S<T*> {};
10869 
10870 	 and supposing that we are instantiating S<int*>, ARGS will
10871 	 presently be {int*} -- but we need {int}.  */
10872       pattern = TREE_TYPE (t);
10873       args = TREE_PURPOSE (t);
10874     }
10875   else
10876     {
10877       pattern = TREE_TYPE (templ);
10878       args = CLASSTYPE_TI_ARGS (type);
10879     }
10880 
10881   /* If the template we're instantiating is incomplete, then clearly
10882      there's nothing we can do.  */
10883   if (!COMPLETE_TYPE_P (pattern))
10884     {
10885       /* We can try again later.  */
10886       TYPE_BEING_DEFINED (type) = 0;
10887       return type;
10888     }
10889 
10890   /* If we've recursively instantiated too many templates, stop.  */
10891   if (! push_tinst_level (type))
10892     return type;
10893 
10894   /* We may be in the middle of deferred access check.  Disable
10895      it now.  */
10896   push_deferring_access_checks (dk_no_deferred);
10897 
10898   int saved_unevaluated_operand = cp_unevaluated_operand;
10899   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
10900 
10901   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
10902   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
10903   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
10904     fn_context = error_mark_node;
10905   if (!fn_context)
10906     push_to_top_level ();
10907   else
10908     {
10909       cp_unevaluated_operand = 0;
10910       c_inhibit_evaluation_warnings = 0;
10911     }
10912   /* Use #pragma pack from the template context.  */
10913   saved_maximum_field_alignment = maximum_field_alignment;
10914   maximum_field_alignment = TYPE_PRECISION (pattern);
10915 
10916   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
10917 
10918   /* Set the input location to the most specialized template definition.
10919      This is needed if tsubsting causes an error.  */
10920   typedecl = TYPE_MAIN_DECL (pattern);
10921   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
10922     DECL_SOURCE_LOCATION (typedecl);
10923 
10924   TYPE_PACKED (type) = TYPE_PACKED (pattern);
10925   SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
10926   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
10927   CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
10928   if (ANON_AGGR_TYPE_P (pattern))
10929     SET_ANON_AGGR_TYPE_P (type);
10930   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
10931     {
10932       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
10933       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
10934       /* Adjust visibility for template arguments.  */
10935       determine_visibility (TYPE_MAIN_DECL (type));
10936     }
10937   if (CLASS_TYPE_P (type))
10938     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
10939 
10940   pbinfo = TYPE_BINFO (pattern);
10941 
10942   /* We should never instantiate a nested class before its enclosing
10943      class; we need to look up the nested class by name before we can
10944      instantiate it, and that lookup should instantiate the enclosing
10945      class.  */
10946   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
10947 	      || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
10948 
10949   base_list = NULL_TREE;
10950   if (BINFO_N_BASE_BINFOS (pbinfo))
10951     {
10952       tree pbase_binfo;
10953       tree pushed_scope;
10954       int i;
10955 
10956       /* We must enter the scope containing the type, as that is where
10957 	 the accessibility of types named in dependent bases are
10958 	 looked up from.  */
10959       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
10960 
10961       /* Substitute into each of the bases to determine the actual
10962 	 basetypes.  */
10963       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
10964 	{
10965 	  tree base;
10966 	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
10967           tree expanded_bases = NULL_TREE;
10968           int idx, len = 1;
10969 
10970           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
10971             {
10972               expanded_bases =
10973 		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
10974 				       args, tf_error, NULL_TREE);
10975               if (expanded_bases == error_mark_node)
10976                 continue;
10977 
10978               len = TREE_VEC_LENGTH (expanded_bases);
10979             }
10980 
10981           for (idx = 0; idx < len; idx++)
10982             {
10983               if (expanded_bases)
10984                 /* Extract the already-expanded base class.  */
10985                 base = TREE_VEC_ELT (expanded_bases, idx);
10986               else
10987                 /* Substitute to figure out the base class.  */
10988                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
10989                                NULL_TREE);
10990 
10991               if (base == error_mark_node)
10992                 continue;
10993 
10994               base_list = tree_cons (access, base, base_list);
10995               if (BINFO_VIRTUAL_P (pbase_binfo))
10996                 TREE_TYPE (base_list) = integer_type_node;
10997             }
10998 	}
10999 
11000       /* The list is now in reverse order; correct that.  */
11001       base_list = nreverse (base_list);
11002 
11003       if (pushed_scope)
11004 	pop_scope (pushed_scope);
11005     }
11006   /* Now call xref_basetypes to set up all the base-class
11007      information.  */
11008   xref_basetypes (type, base_list);
11009 
11010   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
11011 				  (int) ATTR_FLAG_TYPE_IN_PLACE,
11012 				  args, tf_error, NULL_TREE);
11013   fixup_attribute_variants (type);
11014 
11015   /* Now that our base classes are set up, enter the scope of the
11016      class, so that name lookups into base classes, etc. will work
11017      correctly.  This is precisely analogous to what we do in
11018      begin_class_definition when defining an ordinary non-template
11019      class, except we also need to push the enclosing classes.  */
11020   push_nested_class (type);
11021 
11022   /* Now members are processed in the order of declaration.  */
11023   for (member = CLASSTYPE_DECL_LIST (pattern);
11024        member; member = TREE_CHAIN (member))
11025     {
11026       tree t = TREE_VALUE (member);
11027 
11028       if (TREE_PURPOSE (member))
11029 	{
11030 	  if (TYPE_P (t))
11031 	    {
11032 	      if (LAMBDA_TYPE_P (t))
11033 		/* A closure type for a lambda in an NSDMI or default argument.
11034 		   Ignore it; it will be regenerated when needed.  */
11035 		continue;
11036 
11037 	      /* Build new CLASSTYPE_NESTED_UTDS.  */
11038 
11039 	      tree newtag;
11040 	      bool class_template_p;
11041 
11042 	      class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
11043 				  && TYPE_LANG_SPECIFIC (t)
11044 				  && CLASSTYPE_IS_TEMPLATE (t));
11045 	      /* If the member is a class template, then -- even after
11046 		 substitution -- there may be dependent types in the
11047 		 template argument list for the class.  We increment
11048 		 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
11049 		 that function will assume that no types are dependent
11050 		 when outside of a template.  */
11051 	      if (class_template_p)
11052 		++processing_template_decl;
11053 	      newtag = tsubst (t, args, tf_error, NULL_TREE);
11054 	      if (class_template_p)
11055 		--processing_template_decl;
11056 	      if (newtag == error_mark_node)
11057 		continue;
11058 
11059 	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
11060 		{
11061 		  tree name = TYPE_IDENTIFIER (t);
11062 
11063 		  if (class_template_p)
11064 		    /* Unfortunately, lookup_template_class sets
11065 		       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
11066 		       instantiation (i.e., for the type of a member
11067 		       template class nested within a template class.)
11068 		       This behavior is required for
11069 		       maybe_process_partial_specialization to work
11070 		       correctly, but is not accurate in this case;
11071 		       the TAG is not an instantiation of anything.
11072 		       (The corresponding TEMPLATE_DECL is an
11073 		       instantiation, but the TYPE is not.) */
11074 		    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
11075 
11076 		  /* Now, we call pushtag to put this NEWTAG into the scope of
11077 		     TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
11078 		     pushtag calling push_template_decl.  We don't have to do
11079 		     this for enums because it will already have been done in
11080 		     tsubst_enum.  */
11081 		  if (name)
11082 		    SET_IDENTIFIER_TYPE_VALUE (name, newtag);
11083 		  pushtag (name, newtag, /*tag_scope=*/ts_current);
11084 		}
11085 	    }
11086 	  else if (DECL_DECLARES_FUNCTION_P (t))
11087 	    {
11088 	      tree r;
11089 
11090 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11091 		++processing_template_decl;
11092 	      r = tsubst (t, args, tf_error, NULL_TREE);
11093 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11094 		--processing_template_decl;
11095 	      set_current_access_from_decl (r);
11096 	      finish_member_declaration (r);
11097 	      /* Instantiate members marked with attribute used.  */
11098 	      if (r != error_mark_node && DECL_PRESERVE_P (r))
11099 		mark_used (r);
11100 	      if (TREE_CODE (r) == FUNCTION_DECL
11101 		  && DECL_OMP_DECLARE_REDUCTION_P (r))
11102 		cp_check_omp_declare_reduction (r);
11103 	    }
11104 	  else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
11105 		   && LAMBDA_TYPE_P (TREE_TYPE (t)))
11106 	    /* A closure type for a lambda in an NSDMI or default argument.
11107 	       Ignore it; it will be regenerated when needed.  */;
11108 	  else
11109 	    {
11110 	      /* Build new TYPE_FIELDS.  */
11111               if (TREE_CODE (t) == STATIC_ASSERT)
11112                 {
11113                   tree condition;
11114 
11115 		  ++c_inhibit_evaluation_warnings;
11116 		  condition =
11117 		    tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
11118 				 tf_warning_or_error, NULL_TREE,
11119 				 /*integral_constant_expression_p=*/true);
11120 		  --c_inhibit_evaluation_warnings;
11121 
11122                   finish_static_assert (condition,
11123                                         STATIC_ASSERT_MESSAGE (t),
11124                                         STATIC_ASSERT_SOURCE_LOCATION (t),
11125                                         /*member_p=*/true);
11126                 }
11127 	      else if (TREE_CODE (t) != CONST_DECL)
11128 		{
11129 		  tree r;
11130 		  tree vec = NULL_TREE;
11131 		  int len = 1;
11132 
11133 		  /* The file and line for this declaration, to
11134 		     assist in error message reporting.  Since we
11135 		     called push_tinst_level above, we don't need to
11136 		     restore these.  */
11137 		  input_location = DECL_SOURCE_LOCATION (t);
11138 
11139 		  if (TREE_CODE (t) == TEMPLATE_DECL)
11140 		    ++processing_template_decl;
11141 		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
11142 		  if (TREE_CODE (t) == TEMPLATE_DECL)
11143 		    --processing_template_decl;
11144 
11145 		  if (TREE_CODE (r) == TREE_VEC)
11146 		    {
11147 		      /* A capture pack became multiple fields.  */
11148 		      vec = r;
11149 		      len = TREE_VEC_LENGTH (vec);
11150 		    }
11151 
11152 		  for (int i = 0; i < len; ++i)
11153 		    {
11154 		      if (vec)
11155 			r = TREE_VEC_ELT (vec, i);
11156 		      if (VAR_P (r))
11157 			{
11158 			  /* In [temp.inst]:
11159 
11160 			     [t]he initialization (and any associated
11161 			     side-effects) of a static data member does
11162 			     not occur unless the static data member is
11163 			     itself used in a way that requires the
11164 			     definition of the static data member to
11165 			     exist.
11166 
11167 			     Therefore, we do not substitute into the
11168 			     initialized for the static data member here.  */
11169 			  finish_static_data_member_decl
11170 			    (r,
11171 			     /*init=*/NULL_TREE,
11172 			     /*init_const_expr_p=*/false,
11173 			     /*asmspec_tree=*/NULL_TREE,
11174 			     /*flags=*/0);
11175 			  /* Instantiate members marked with attribute used. */
11176 			  if (r != error_mark_node && DECL_PRESERVE_P (r))
11177 			    mark_used (r);
11178 			}
11179 		      else if (TREE_CODE (r) == FIELD_DECL)
11180 			{
11181 			  /* Determine whether R has a valid type and can be
11182 			     completed later.  If R is invalid, then its type
11183 			     is replaced by error_mark_node.  */
11184 			  tree rtype = TREE_TYPE (r);
11185 			  if (can_complete_type_without_circularity (rtype))
11186 			    complete_type (rtype);
11187 
11188 			  if (!complete_or_array_type_p (rtype))
11189 			    {
11190 			      /* If R's type couldn't be completed and
11191 				 it isn't a flexible array member (whose
11192 				 type is incomplete by definition) give
11193 				 an error.  */
11194 			      cxx_incomplete_type_error (r, rtype);
11195 			      TREE_TYPE (r) = error_mark_node;
11196 			    }
11197 			  else if (TREE_CODE (rtype) == ARRAY_TYPE
11198 				   && TYPE_DOMAIN (rtype) == NULL_TREE
11199 				   && (TREE_CODE (type) == UNION_TYPE
11200 				       || TREE_CODE (type) == QUAL_UNION_TYPE))
11201 			    {
11202 			      error ("flexible array member %qD in union", r);
11203 			      TREE_TYPE (r) = error_mark_node;
11204 			    }
11205 			}
11206 
11207 		      /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
11208 			 such a thing will already have been added to the field
11209 			 list by tsubst_enum in finish_member_declaration in the
11210 			 CLASSTYPE_NESTED_UTDS case above.  */
11211 		      if (!(TREE_CODE (r) == TYPE_DECL
11212 			    && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
11213 			    && DECL_ARTIFICIAL (r)))
11214 			{
11215 			  set_current_access_from_decl (r);
11216 			  finish_member_declaration (r);
11217 			}
11218 		    }
11219 		}
11220 	    }
11221 	}
11222       else
11223 	{
11224 	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
11225 	      || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11226 	    {
11227 	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
11228 
11229 	      tree friend_type = t;
11230 	      bool adjust_processing_template_decl = false;
11231 
11232 	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11233 		{
11234 		  /* template <class T> friend class C;  */
11235 		  friend_type = tsubst_friend_class (friend_type, args);
11236 		  adjust_processing_template_decl = true;
11237 		}
11238 	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
11239 		{
11240 		  /* template <class T> friend class C::D;  */
11241 		  friend_type = tsubst (friend_type, args,
11242 					tf_warning_or_error, NULL_TREE);
11243 		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11244 		    friend_type = TREE_TYPE (friend_type);
11245 		  adjust_processing_template_decl = true;
11246 		}
11247 	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE
11248 		       || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
11249 		{
11250 		  /* This could be either
11251 
11252 		       friend class T::C;
11253 
11254 		     when dependent_type_p is false or
11255 
11256 		       template <class U> friend class T::C;
11257 
11258 		     otherwise.  */
11259 		  /* Bump processing_template_decl in case this is something like
11260 		     template <class T> friend struct A<T>::B.  */
11261 		  ++processing_template_decl;
11262 		  friend_type = tsubst (friend_type, args,
11263 					tf_warning_or_error, NULL_TREE);
11264 		  if (dependent_type_p (friend_type))
11265 		    adjust_processing_template_decl = true;
11266 		  --processing_template_decl;
11267 		}
11268 	      else if (TREE_CODE (friend_type) != BOUND_TEMPLATE_TEMPLATE_PARM
11269 		       && !CLASSTYPE_USE_TEMPLATE (friend_type)
11270 		       && TYPE_HIDDEN_P (friend_type))
11271 		{
11272 		  /* friend class C;
11273 
11274 		     where C hasn't been declared yet.  Let's lookup name
11275 		     from namespace scope directly, bypassing any name that
11276 		     come from dependent base class.  */
11277 		  tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
11278 
11279 		  /* The call to xref_tag_from_type does injection for friend
11280 		     classes.  */
11281 		  push_nested_namespace (ns);
11282 		  friend_type =
11283 		    xref_tag_from_type (friend_type, NULL_TREE,
11284 					/*tag_scope=*/ts_current);
11285 		  pop_nested_namespace (ns);
11286 		}
11287 	      else if (uses_template_parms (friend_type))
11288 		/* friend class C<T>;  */
11289 		friend_type = tsubst (friend_type, args,
11290 				      tf_warning_or_error, NULL_TREE);
11291 	      /* Otherwise it's
11292 
11293 		   friend class C;
11294 
11295 		 where C is already declared or
11296 
11297 		   friend class C<int>;
11298 
11299 		 We don't have to do anything in these cases.  */
11300 
11301 	      if (adjust_processing_template_decl)
11302 		/* Trick make_friend_class into realizing that the friend
11303 		   we're adding is a template, not an ordinary class.  It's
11304 		   important that we use make_friend_class since it will
11305 		   perform some error-checking and output cross-reference
11306 		   information.  */
11307 		++processing_template_decl;
11308 
11309 	      if (friend_type != error_mark_node)
11310 		make_friend_class (type, friend_type, /*complain=*/false);
11311 
11312 	      if (adjust_processing_template_decl)
11313 		--processing_template_decl;
11314 	    }
11315 	  else
11316 	    {
11317 	      /* Build new DECL_FRIENDLIST.  */
11318 	      tree r;
11319 
11320 	      /* The file and line for this declaration, to
11321 		 assist in error message reporting.  Since we
11322 		 called push_tinst_level above, we don't need to
11323 		 restore these.  */
11324 	      input_location = DECL_SOURCE_LOCATION (t);
11325 
11326 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11327 		{
11328 		  ++processing_template_decl;
11329 		  push_deferring_access_checks (dk_no_check);
11330 		}
11331 
11332 	      r = tsubst_friend_function (t, args);
11333 	      add_friend (type, r, /*complain=*/false);
11334 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11335 		{
11336 		  pop_deferring_access_checks ();
11337 		  --processing_template_decl;
11338 		}
11339 	    }
11340 	}
11341     }
11342 
11343   if (fn_context)
11344     {
11345       /* Restore these before substituting into the lambda capture
11346 	 initializers.  */
11347       cp_unevaluated_operand = saved_unevaluated_operand;
11348       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
11349     }
11350 
11351   /* Set the file and line number information to whatever is given for
11352      the class itself.  This puts error messages involving generated
11353      implicit functions at a predictable point, and the same point
11354      that would be used for non-template classes.  */
11355   input_location = DECL_SOURCE_LOCATION (typedecl);
11356 
11357   unreverse_member_declarations (type);
11358   finish_struct_1 (type);
11359   TYPE_BEING_DEFINED (type) = 0;
11360 
11361   /* We don't instantiate default arguments for member functions.  14.7.1:
11362 
11363      The implicit instantiation of a class template specialization causes
11364      the implicit instantiation of the declarations, but not of the
11365      definitions or default arguments, of the class member functions,
11366      member classes, static data members and member templates....  */
11367 
11368   /* Some typedefs referenced from within the template code need to be access
11369      checked at template instantiation time, i.e now. These types were
11370      added to the template at parsing time. Let's get those and perform
11371      the access checks then.  */
11372   perform_typedefs_access_check (pattern, args);
11373   perform_deferred_access_checks (tf_warning_or_error);
11374   pop_nested_class ();
11375   maximum_field_alignment = saved_maximum_field_alignment;
11376   if (!fn_context)
11377     pop_from_top_level ();
11378   pop_deferring_access_checks ();
11379   pop_tinst_level ();
11380 
11381   /* The vtable for a template class can be emitted in any translation
11382      unit in which the class is instantiated.  When there is no key
11383      method, however, finish_struct_1 will already have added TYPE to
11384      the keyed_classes.  */
11385   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
11386     vec_safe_push (keyed_classes, type);
11387 
11388   return type;
11389 }
11390 
11391 /* Wrapper for instantiate_class_template_1.  */
11392 
11393 tree
11394 instantiate_class_template (tree type)
11395 {
11396   tree ret;
11397   timevar_push (TV_TEMPLATE_INST);
11398   ret = instantiate_class_template_1 (type);
11399   timevar_pop (TV_TEMPLATE_INST);
11400   return ret;
11401 }
11402 
11403 static tree
11404 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11405 {
11406   tree r;
11407 
11408   if (!t)
11409     r = t;
11410   else if (TYPE_P (t))
11411     r = tsubst (t, args, complain, in_decl);
11412   else
11413     {
11414       if (!(complain & tf_warning))
11415 	++c_inhibit_evaluation_warnings;
11416       r = tsubst_expr (t, args, complain, in_decl,
11417 		       /*integral_constant_expression_p=*/true);
11418       if (!(complain & tf_warning))
11419 	--c_inhibit_evaluation_warnings;
11420     }
11421   return r;
11422 }
11423 
11424 /* Given a function parameter pack TMPL_PARM and some function parameters
11425    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
11426    and set *SPEC_P to point at the next point in the list.  */
11427 
11428 tree
11429 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
11430 {
11431   /* Collect all of the extra "packed" parameters into an
11432      argument pack.  */
11433   tree parmvec;
11434   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
11435   tree spec_parm = *spec_p;
11436   int i, len;
11437 
11438   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
11439     if (tmpl_parm
11440 	&& !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
11441       break;
11442 
11443   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
11444   parmvec = make_tree_vec (len);
11445   spec_parm = *spec_p;
11446   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
11447     {
11448       tree elt = spec_parm;
11449       if (DECL_PACK_P (elt))
11450 	elt = make_pack_expansion (elt);
11451       TREE_VEC_ELT (parmvec, i) = elt;
11452     }
11453 
11454   /* Build the argument packs.  */
11455   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
11456   *spec_p = spec_parm;
11457 
11458   return argpack;
11459 }
11460 
11461 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
11462    NONTYPE_ARGUMENT_PACK.  */
11463 
11464 static tree
11465 make_fnparm_pack (tree spec_parm)
11466 {
11467   return extract_fnparm_pack (NULL_TREE, &spec_parm);
11468 }
11469 
11470 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
11471    pack expansion with no extra args, 2 if it has extra args, or 0
11472    if it is not a pack expansion.  */
11473 
11474 static int
11475 argument_pack_element_is_expansion_p (tree arg_pack, int i)
11476 {
11477   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
11478   if (i >= TREE_VEC_LENGTH (vec))
11479     return 0;
11480   tree elt = TREE_VEC_ELT (vec, i);
11481   if (DECL_P (elt))
11482     /* A decl pack is itself an expansion.  */
11483     elt = TREE_TYPE (elt);
11484   if (!PACK_EXPANSION_P (elt))
11485     return 0;
11486   if (PACK_EXPANSION_EXTRA_ARGS (elt))
11487     return 2;
11488   return 1;
11489 }
11490 
11491 
11492 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
11493 
11494 static tree
11495 make_argument_pack_select (tree arg_pack, unsigned index)
11496 {
11497   tree aps = make_node (ARGUMENT_PACK_SELECT);
11498 
11499   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
11500   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11501 
11502   return aps;
11503 }
11504 
11505 /*  This is a subroutine of tsubst_pack_expansion.
11506 
11507     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
11508     mechanism to store the (non complete list of) arguments of the
11509     substitution and return a non substituted pack expansion, in order
11510     to wait for when we have enough arguments to really perform the
11511     substitution.  */
11512 
11513 static bool
11514 use_pack_expansion_extra_args_p (tree parm_packs,
11515 				 int arg_pack_len,
11516 				 bool has_empty_arg)
11517 {
11518   /* If one pack has an expansion and another pack has a normal
11519      argument or if one pack has an empty argument and an another
11520      one hasn't then tsubst_pack_expansion cannot perform the
11521      substitution and need to fall back on the
11522      PACK_EXPANSION_EXTRA mechanism.  */
11523   if (parm_packs == NULL_TREE)
11524     return false;
11525   else if (has_empty_arg)
11526     return true;
11527 
11528   bool has_expansion_arg = false;
11529   for (int i = 0 ; i < arg_pack_len; ++i)
11530     {
11531       bool has_non_expansion_arg = false;
11532       for (tree parm_pack = parm_packs;
11533 	   parm_pack;
11534 	   parm_pack = TREE_CHAIN (parm_pack))
11535 	{
11536 	  tree arg = TREE_VALUE (parm_pack);
11537 
11538 	  int exp = argument_pack_element_is_expansion_p (arg, i);
11539 	  if (exp == 2)
11540 	    /* We can't substitute a pack expansion with extra args into
11541 	       our pattern.  */
11542 	    return true;
11543 	  else if (exp)
11544 	    has_expansion_arg = true;
11545 	  else
11546 	    has_non_expansion_arg = true;
11547 	}
11548 
11549       if (has_expansion_arg && has_non_expansion_arg)
11550 	return true;
11551     }
11552   return false;
11553 }
11554 
11555 /* [temp.variadic]/6 says that:
11556 
11557        The instantiation of a pack expansion [...]
11558        produces a list E1,E2, ..., En, where N is the number of elements
11559        in the pack expansion parameters.
11560 
11561    This subroutine of tsubst_pack_expansion produces one of these Ei.
11562 
11563    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
11564    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
11565    PATTERN, and each TREE_VALUE is its corresponding argument pack.
11566    INDEX is the index 'i' of the element Ei to produce.  ARGS,
11567    COMPLAIN, and IN_DECL are the same parameters as for the
11568    tsubst_pack_expansion function.
11569 
11570    The function returns the resulting Ei upon successful completion,
11571    or error_mark_node.
11572 
11573    Note that this function possibly modifies the ARGS parameter, so
11574    it's the responsibility of the caller to restore it.  */
11575 
11576 static tree
11577 gen_elem_of_pack_expansion_instantiation (tree pattern,
11578 					  tree parm_packs,
11579 					  unsigned index,
11580 					  tree args /* This parm gets
11581 						       modified.  */,
11582 					  tsubst_flags_t complain,
11583 					  tree in_decl)
11584 {
11585   tree t;
11586   bool ith_elem_is_expansion = false;
11587 
11588   /* For each parameter pack, change the substitution of the parameter
11589      pack to the ith argument in its argument pack, then expand the
11590      pattern.  */
11591   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
11592     {
11593       tree parm = TREE_PURPOSE (pack);
11594       tree arg_pack = TREE_VALUE (pack);
11595       tree aps;			/* instance of ARGUMENT_PACK_SELECT.  */
11596 
11597       ith_elem_is_expansion |=
11598 	argument_pack_element_is_expansion_p (arg_pack, index);
11599 
11600       /* Select the Ith argument from the pack.  */
11601       if (TREE_CODE (parm) == PARM_DECL
11602 	  || VAR_P (parm)
11603 	  || TREE_CODE (parm) == FIELD_DECL)
11604 	{
11605 	  if (index == 0)
11606 	    {
11607 	      aps = make_argument_pack_select (arg_pack, index);
11608 	      if (!mark_used (parm, complain) && !(complain & tf_error))
11609 		return error_mark_node;
11610 	      register_local_specialization (aps, parm);
11611 	    }
11612 	  else
11613 	    aps = retrieve_local_specialization (parm);
11614 	}
11615       else
11616 	{
11617 	  int idx, level;
11618 	  template_parm_level_and_index (parm, &level, &idx);
11619 
11620 	  if (index == 0)
11621 	    {
11622 	      aps = make_argument_pack_select (arg_pack, index);
11623 	      /* Update the corresponding argument.  */
11624 	      TMPL_ARG (args, level, idx) = aps;
11625 	    }
11626 	  else
11627 	    /* Re-use the ARGUMENT_PACK_SELECT.  */
11628 	    aps = TMPL_ARG (args, level, idx);
11629 	}
11630       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11631     }
11632 
11633   /* Substitute into the PATTERN with the (possibly altered)
11634      arguments.  */
11635   if (pattern == in_decl)
11636     /* Expanding a fixed parameter pack from
11637        coerce_template_parameter_pack.  */
11638     t = tsubst_decl (pattern, args, complain);
11639   else if (pattern == error_mark_node)
11640     t = error_mark_node;
11641   else if (constraint_p (pattern))
11642     {
11643       if (processing_template_decl)
11644 	t = tsubst_constraint (pattern, args, complain, in_decl);
11645       else
11646 	t = (constraints_satisfied_p (pattern, args)
11647 	     ? boolean_true_node : boolean_false_node);
11648     }
11649   else if (!TYPE_P (pattern))
11650     t = tsubst_expr (pattern, args, complain, in_decl,
11651 		     /*integral_constant_expression_p=*/false);
11652   else
11653     t = tsubst (pattern, args, complain, in_decl);
11654 
11655   /*  If the Ith argument pack element is a pack expansion, then
11656       the Ith element resulting from the substituting is going to
11657       be a pack expansion as well.  */
11658   if (ith_elem_is_expansion)
11659     t = make_pack_expansion (t, complain);
11660 
11661   return t;
11662 }
11663 
11664 /* When the unexpanded parameter pack in a fold expression expands to an empty
11665    sequence, the value of the expression is as follows; the program is
11666    ill-formed if the operator is not listed in this table.
11667 
11668    &&	true
11669    ||	false
11670    ,	void()  */
11671 
11672 tree
11673 expand_empty_fold (tree t, tsubst_flags_t complain)
11674 {
11675   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
11676   if (!FOLD_EXPR_MODIFY_P (t))
11677     switch (code)
11678       {
11679       case TRUTH_ANDIF_EXPR:
11680 	return boolean_true_node;
11681       case TRUTH_ORIF_EXPR:
11682 	return boolean_false_node;
11683       case COMPOUND_EXPR:
11684 	return void_node;
11685       default:
11686 	break;
11687       }
11688 
11689   if (complain & tf_error)
11690     error_at (location_of (t),
11691 	      "fold of empty expansion over %O", code);
11692   return error_mark_node;
11693 }
11694 
11695 /* Given a fold-expression T and a current LEFT and RIGHT operand,
11696    form an expression that combines the two terms using the
11697    operator of T. */
11698 
11699 static tree
11700 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
11701 {
11702   tree op = FOLD_EXPR_OP (t);
11703   tree_code code = (tree_code)TREE_INT_CST_LOW (op);
11704 
11705   // Handle compound assignment operators.
11706   if (FOLD_EXPR_MODIFY_P (t))
11707     return build_x_modify_expr (input_location, left, code, right, complain);
11708 
11709   switch (code)
11710     {
11711     case COMPOUND_EXPR:
11712       return build_x_compound_expr (input_location, left, right, complain);
11713     case DOTSTAR_EXPR:
11714       return build_m_component_ref (left, right, complain);
11715     default:
11716       return build_x_binary_op (input_location, code,
11717                                 left, TREE_CODE (left),
11718                                 right, TREE_CODE (right),
11719                                 /*overload=*/NULL,
11720                                 complain);
11721     }
11722 }
11723 
11724 /* Substitute ARGS into the pack of a fold expression T. */
11725 
11726 static inline tree
11727 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11728 {
11729   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
11730 }
11731 
11732 /* Substitute ARGS into the pack of a fold expression T. */
11733 
11734 static inline tree
11735 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11736 {
11737   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
11738 }
11739 
11740 /* Expand a PACK of arguments into a grouped as left fold.
11741    Given a pack containing elements A0, A1, ..., An and an
11742    operator @, this builds the expression:
11743 
11744       ((A0 @ A1) @ A2) ... @ An
11745 
11746    Note that PACK must not be empty.
11747 
11748    The operator is defined by the original fold expression T. */
11749 
11750 static tree
11751 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
11752 {
11753   tree left = TREE_VEC_ELT (pack, 0);
11754   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
11755     {
11756       tree right = TREE_VEC_ELT (pack, i);
11757       left = fold_expression (t, left, right, complain);
11758     }
11759   return left;
11760 }
11761 
11762 /* Substitute into a unary left fold expression. */
11763 
11764 static tree
11765 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
11766                         tree in_decl)
11767 {
11768   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11769   if (pack == error_mark_node)
11770     return error_mark_node;
11771   if (PACK_EXPANSION_P (pack))
11772     {
11773       tree r = copy_node (t);
11774       FOLD_EXPR_PACK (r) = pack;
11775       return r;
11776     }
11777   if (TREE_VEC_LENGTH (pack) == 0)
11778     return expand_empty_fold (t, complain);
11779   else
11780     return expand_left_fold (t, pack, complain);
11781 }
11782 
11783 /* Substitute into a binary left fold expression.
11784 
11785    Do ths by building a single (non-empty) vector of argumnts and
11786    building the expression from those elements. */
11787 
11788 static tree
11789 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
11790                          tree in_decl)
11791 {
11792   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11793   if (pack == error_mark_node)
11794     return error_mark_node;
11795   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11796   if (init == error_mark_node)
11797     return error_mark_node;
11798 
11799   if (PACK_EXPANSION_P (pack))
11800     {
11801       tree r = copy_node (t);
11802       FOLD_EXPR_PACK (r) = pack;
11803       FOLD_EXPR_INIT (r) = init;
11804       return r;
11805     }
11806 
11807   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
11808   TREE_VEC_ELT (vec, 0) = init;
11809   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
11810     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
11811 
11812   return expand_left_fold (t, vec, complain);
11813 }
11814 
11815 /* Expand a PACK of arguments into a grouped as right fold.
11816    Given a pack containing elementns A0, A1, ..., and an
11817    operator @, this builds the expression:
11818 
11819       A0@ ... (An-2 @ (An-1 @ An))
11820 
11821    Note that PACK must not be empty.
11822 
11823    The operator is defined by the original fold expression T. */
11824 
11825 tree
11826 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
11827 {
11828   // Build the expression.
11829   int n = TREE_VEC_LENGTH (pack);
11830   tree right = TREE_VEC_ELT (pack, n - 1);
11831   for (--n; n != 0; --n)
11832     {
11833       tree left = TREE_VEC_ELT (pack, n - 1);
11834       right = fold_expression (t, left, right, complain);
11835     }
11836   return right;
11837 }
11838 
11839 /* Substitute into a unary right fold expression. */
11840 
11841 static tree
11842 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
11843                          tree in_decl)
11844 {
11845   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11846   if (pack == error_mark_node)
11847     return error_mark_node;
11848   if (PACK_EXPANSION_P (pack))
11849     {
11850       tree r = copy_node (t);
11851       FOLD_EXPR_PACK (r) = pack;
11852       return r;
11853     }
11854   if (TREE_VEC_LENGTH (pack) == 0)
11855     return expand_empty_fold (t, complain);
11856   else
11857     return expand_right_fold (t, pack, complain);
11858 }
11859 
11860 /* Substitute into a binary right fold expression.
11861 
11862    Do ths by building a single (non-empty) vector of arguments and
11863    building the expression from those elements. */
11864 
11865 static tree
11866 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
11867                          tree in_decl)
11868 {
11869   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11870   if (pack == error_mark_node)
11871     return error_mark_node;
11872   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11873   if (init == error_mark_node)
11874     return error_mark_node;
11875 
11876   if (PACK_EXPANSION_P (pack))
11877     {
11878       tree r = copy_node (t);
11879       FOLD_EXPR_PACK (r) = pack;
11880       FOLD_EXPR_INIT (r) = init;
11881       return r;
11882     }
11883 
11884   int n = TREE_VEC_LENGTH (pack);
11885   tree vec = make_tree_vec (n + 1);
11886   for (int i = 0; i < n; ++i)
11887     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
11888   TREE_VEC_ELT (vec, n) = init;
11889 
11890   return expand_right_fold (t, vec, complain);
11891 }
11892 
11893 /* Walk through the pattern of a pack expansion, adding everything in
11894    local_specializations to a list.  */
11895 
11896 struct el_data
11897 {
11898   hash_set<tree> internal;
11899   tree extra;
11900   tsubst_flags_t complain;
11901 
11902   el_data (tsubst_flags_t c)
11903     : extra (NULL_TREE), complain (c) {}
11904 };
11905 static tree
11906 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
11907 {
11908   el_data &data = *reinterpret_cast<el_data*>(data_);
11909   tree *extra = &data.extra;
11910   tsubst_flags_t complain = data.complain;
11911 
11912   if (TYPE_P (*tp) && typedef_variant_p (*tp))
11913     /* Remember local typedefs (85214).  */
11914     tp = &TYPE_NAME (*tp);
11915 
11916   if (TREE_CODE (*tp) == DECL_EXPR)
11917     data.internal.add (DECL_EXPR_DECL (*tp));
11918   else if (tree spec = retrieve_local_specialization (*tp))
11919     {
11920       if (data.internal.contains (*tp))
11921 	/* Don't mess with variables declared within the pattern.  */
11922 	return NULL_TREE;
11923       if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
11924 	{
11925 	  /* Maybe pull out the PARM_DECL for a partial instantiation.  */
11926 	  tree args = ARGUMENT_PACK_ARGS (spec);
11927 	  if (TREE_VEC_LENGTH (args) == 1)
11928 	    {
11929 	      tree elt = TREE_VEC_ELT (args, 0);
11930 	      if (PACK_EXPANSION_P (elt))
11931 		elt = PACK_EXPANSION_PATTERN (elt);
11932 	      if (DECL_PACK_P (elt))
11933 		spec = elt;
11934 	    }
11935 	  if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
11936 	    {
11937 	      /* Handle lambda capture here, since we aren't doing any
11938 		 substitution now, and so tsubst_copy won't call
11939 		 process_outer_var_ref.  */
11940 	      tree args = ARGUMENT_PACK_ARGS (spec);
11941 	      int len = TREE_VEC_LENGTH (args);
11942 	      for (int i = 0; i < len; ++i)
11943 		{
11944 		  tree arg = TREE_VEC_ELT (args, i);
11945 		  tree carg = arg;
11946 		  if (outer_automatic_var_p (arg))
11947 		    carg = process_outer_var_ref (arg, complain);
11948 		  if (carg != arg)
11949 		    {
11950 		      /* Make a new NONTYPE_ARGUMENT_PACK of the capture
11951 			 proxies.  */
11952 		      if (i == 0)
11953 			{
11954 			  spec = copy_node (spec);
11955 			  args = copy_node (args);
11956 			  SET_ARGUMENT_PACK_ARGS (spec, args);
11957 			  register_local_specialization (spec, *tp);
11958 			}
11959 		      TREE_VEC_ELT (args, i) = carg;
11960 		    }
11961 		}
11962 	    }
11963 	}
11964       if (outer_automatic_var_p (spec))
11965 	spec = process_outer_var_ref (spec, complain);
11966       *extra = tree_cons (*tp, spec, *extra);
11967     }
11968   return NULL_TREE;
11969 }
11970 static tree
11971 extract_local_specs (tree pattern, tsubst_flags_t complain)
11972 {
11973   el_data data (complain);
11974   cp_walk_tree_without_duplicates (&pattern, extract_locals_r, &data);
11975   return data.extra;
11976 }
11977 
11978 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
11979    for use in PACK_EXPANSION_EXTRA_ARGS.  */
11980 
11981 tree
11982 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
11983 {
11984   tree extra = args;
11985   if (local_specializations)
11986     if (tree locals = extract_local_specs (pattern, complain))
11987       extra = tree_cons (NULL_TREE, extra, locals);
11988   return extra;
11989 }
11990 
11991 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
11992    normal template args to ARGS.  */
11993 
11994 tree
11995 add_extra_args (tree extra, tree args)
11996 {
11997   if (extra && TREE_CODE (extra) == TREE_LIST)
11998     {
11999       for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
12000 	{
12001 	  /* The partial instantiation involved local declarations collected in
12002 	     extract_local_specs; map from the general template to our local
12003 	     context.  */
12004 	  tree gen = TREE_PURPOSE (elt);
12005 	  tree inst = TREE_VALUE (elt);
12006 	  if (DECL_P (inst))
12007 	    if (tree local = retrieve_local_specialization (inst))
12008 	      inst = local;
12009 	  /* else inst is already a full instantiation of the pack.  */
12010 	  register_local_specialization (inst, gen);
12011 	}
12012       gcc_assert (!TREE_PURPOSE (extra));
12013       extra = TREE_VALUE (extra);
12014     }
12015   return add_to_template_args (extra, args);
12016 }
12017 
12018 /* Substitute ARGS into T, which is an pack expansion
12019    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
12020    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
12021    (if only a partial substitution could be performed) or
12022    ERROR_MARK_NODE if there was an error.  */
12023 tree
12024 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
12025 		       tree in_decl)
12026 {
12027   tree pattern;
12028   tree pack, packs = NULL_TREE;
12029   bool unsubstituted_packs = false;
12030   bool unsubstituted_fn_pack = false;
12031   int i, len = -1;
12032   tree result;
12033   hash_map<tree, tree> *saved_local_specializations = NULL;
12034   bool need_local_specializations = false;
12035   int levels;
12036 
12037   gcc_assert (PACK_EXPANSION_P (t));
12038   pattern = PACK_EXPANSION_PATTERN (t);
12039 
12040   /* Add in any args remembered from an earlier partial instantiation.  */
12041   args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
12042 
12043   levels = TMPL_ARGS_DEPTH (args);
12044 
12045   /* Determine the argument packs that will instantiate the parameter
12046      packs used in the expansion expression. While we're at it,
12047      compute the number of arguments to be expanded and make sure it
12048      is consistent.  */
12049   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
12050        pack = TREE_CHAIN (pack))
12051     {
12052       tree parm_pack = TREE_VALUE (pack);
12053       tree arg_pack = NULL_TREE;
12054       tree orig_arg = NULL_TREE;
12055       int level = 0;
12056 
12057       if (TREE_CODE (parm_pack) == BASES)
12058 	{
12059 	  gcc_assert (parm_pack == pattern);
12060 	  if (BASES_DIRECT (parm_pack))
12061 	    return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
12062 							args, complain,
12063 							in_decl, false),
12064 					   complain);
12065 	  else
12066 	    return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
12067 						 args, complain, in_decl,
12068 						 false), complain);
12069 	}
12070       else if (builtin_pack_call_p (parm_pack))
12071 	{
12072 	  /* ??? Support use in other patterns.  */
12073 	  gcc_assert (parm_pack == pattern);
12074 	  return expand_builtin_pack_call (parm_pack, args,
12075 					   complain, in_decl);
12076 	}
12077       else if (TREE_CODE (parm_pack) == PARM_DECL)
12078 	{
12079 	  /* We know we have correct local_specializations if this
12080 	     expansion is at function scope, or if we're dealing with a
12081 	     local parameter in a requires expression; for the latter,
12082 	     tsubst_requires_expr set it up appropriately.  */
12083 	  if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
12084 	    arg_pack = retrieve_local_specialization (parm_pack);
12085 	  else
12086 	    /* We can't rely on local_specializations for a parameter
12087 	       name used later in a function declaration (such as in a
12088 	       late-specified return type).  Even if it exists, it might
12089 	       have the wrong value for a recursive call.  */
12090 	    need_local_specializations = true;
12091 
12092 	  if (!arg_pack)
12093 	    {
12094 	      /* This parameter pack was used in an unevaluated context.  Just
12095 		 make a dummy decl, since it's only used for its type.  */
12096 	      ++cp_unevaluated_operand;
12097 	      arg_pack = tsubst_decl (parm_pack, args, complain);
12098 	      --cp_unevaluated_operand;
12099 	      if (arg_pack && DECL_PACK_P (arg_pack))
12100 		/* Partial instantiation of the parm_pack, we can't build
12101 		   up an argument pack yet.  */
12102 		arg_pack = NULL_TREE;
12103 	      else
12104 		arg_pack = make_fnparm_pack (arg_pack);
12105 	    }
12106 	  else if (argument_pack_element_is_expansion_p (arg_pack, 0))
12107 	    /* This argument pack isn't fully instantiated yet.  We set this
12108 	       flag rather than clear arg_pack because we do want to do the
12109 	       optimization below, and we don't want to substitute directly
12110 	       into the pattern (as that would expose a NONTYPE_ARGUMENT_PACK
12111 	       where it isn't expected).  */
12112 	    unsubstituted_fn_pack = true;
12113 	}
12114       else if (is_normal_capture_proxy (parm_pack))
12115 	{
12116 	  arg_pack = retrieve_local_specialization (parm_pack);
12117 	  if (argument_pack_element_is_expansion_p (arg_pack, 0))
12118 	    unsubstituted_fn_pack = true;
12119 	}
12120       else
12121         {
12122 	  int idx;
12123           template_parm_level_and_index (parm_pack, &level, &idx);
12124 
12125           if (level <= levels)
12126             arg_pack = TMPL_ARG (args, level, idx);
12127         }
12128 
12129       orig_arg = arg_pack;
12130       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12131 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12132 
12133       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
12134 	/* This can only happen if we forget to expand an argument
12135 	   pack somewhere else. Just return an error, silently.  */
12136 	{
12137 	  result = make_tree_vec (1);
12138 	  TREE_VEC_ELT (result, 0) = error_mark_node;
12139 	  return result;
12140 	}
12141 
12142       if (arg_pack)
12143         {
12144           int my_len =
12145             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
12146 
12147 	  /* Don't bother trying to do a partial substitution with
12148 	     incomplete packs; we'll try again after deduction.  */
12149           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
12150             return t;
12151 
12152           if (len < 0)
12153 	    len = my_len;
12154           else if (len != my_len
12155 		   && !unsubstituted_fn_pack)
12156             {
12157 	      if (!(complain & tf_error))
12158 		/* Fail quietly.  */;
12159               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
12160                 error ("mismatched argument pack lengths while expanding %qT",
12161                        pattern);
12162               else
12163                 error ("mismatched argument pack lengths while expanding %qE",
12164                        pattern);
12165               return error_mark_node;
12166             }
12167 
12168           /* Keep track of the parameter packs and their corresponding
12169              argument packs.  */
12170           packs = tree_cons (parm_pack, arg_pack, packs);
12171           TREE_TYPE (packs) = orig_arg;
12172         }
12173       else
12174 	{
12175 	  /* We can't substitute for this parameter pack.  We use a flag as
12176 	     well as the missing_level counter because function parameter
12177 	     packs don't have a level.  */
12178 	  gcc_assert (processing_template_decl || is_auto (parm_pack));
12179 	  unsubstituted_packs = true;
12180 	}
12181     }
12182 
12183   /* If the expansion is just T..., return the matching argument pack, unless
12184      we need to call convert_from_reference on all the elements.  This is an
12185      important optimization; see c++/68422.  */
12186   if (!unsubstituted_packs
12187       && TREE_PURPOSE (packs) == pattern)
12188     {
12189       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
12190 
12191       /* If the argument pack is a single pack expansion, pull it out.  */
12192       if (TREE_VEC_LENGTH (args) == 1
12193 	  && pack_expansion_args_count (args))
12194 	return TREE_VEC_ELT (args, 0);
12195 
12196       /* Types need no adjustment, nor does sizeof..., and if we still have
12197 	 some pack expansion args we won't do anything yet.  */
12198       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
12199 	  || PACK_EXPANSION_SIZEOF_P (t)
12200 	  || pack_expansion_args_count (args))
12201 	return args;
12202       /* Also optimize expression pack expansions if we can tell that the
12203 	 elements won't have reference type.  */
12204       tree type = TREE_TYPE (pattern);
12205       if (type && TREE_CODE (type) != REFERENCE_TYPE
12206 	  && !PACK_EXPANSION_P (type)
12207 	  && !WILDCARD_TYPE_P (type))
12208 	return args;
12209       /* Otherwise use the normal path so we get convert_from_reference.  */
12210     }
12211 
12212   /* We cannot expand this expansion expression, because we don't have
12213      all of the argument packs we need.  */
12214   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
12215     {
12216       /* We got some full packs, but we can't substitute them in until we
12217 	 have values for all the packs.  So remember these until then.  */
12218 
12219       t = make_pack_expansion (pattern, complain);
12220       PACK_EXPANSION_EXTRA_ARGS (t)
12221 	= build_extra_args (pattern, args, complain);
12222       return t;
12223     }
12224   else if (unsubstituted_packs)
12225     {
12226       /* There were no real arguments, we're just replacing a parameter
12227 	 pack with another version of itself. Substitute into the
12228 	 pattern and return a PACK_EXPANSION_*. The caller will need to
12229 	 deal with that.  */
12230       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
12231 	t = tsubst_expr (pattern, args, complain, in_decl,
12232 			 /*integral_constant_expression_p=*/false);
12233       else
12234 	t = tsubst (pattern, args, complain, in_decl);
12235       t = make_pack_expansion (t, complain);
12236       return t;
12237     }
12238 
12239   gcc_assert (len >= 0);
12240 
12241   if (need_local_specializations)
12242     {
12243       /* We're in a late-specified return type, so create our own local
12244 	 specializations map; the current map is either NULL or (in the
12245 	 case of recursive unification) might have bindings that we don't
12246 	 want to use or alter.  */
12247       saved_local_specializations = local_specializations;
12248       local_specializations = new hash_map<tree, tree>;
12249     }
12250 
12251   /* For each argument in each argument pack, substitute into the
12252      pattern.  */
12253   result = make_tree_vec (len);
12254   tree elem_args = copy_template_args (args);
12255   for (i = 0; i < len; ++i)
12256     {
12257       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
12258 						    i,
12259 						    elem_args, complain,
12260 						    in_decl);
12261       TREE_VEC_ELT (result, i) = t;
12262       if (t == error_mark_node)
12263 	{
12264 	  result = error_mark_node;
12265 	  break;
12266 	}
12267     }
12268 
12269   /* Update ARGS to restore the substitution from parameter packs to
12270      their argument packs.  */
12271   for (pack = packs; pack; pack = TREE_CHAIN (pack))
12272     {
12273       tree parm = TREE_PURPOSE (pack);
12274 
12275       if (TREE_CODE (parm) == PARM_DECL
12276 	  || VAR_P (parm)
12277 	  || TREE_CODE (parm) == FIELD_DECL)
12278         register_local_specialization (TREE_TYPE (pack), parm);
12279       else
12280         {
12281           int idx, level;
12282 
12283 	  if (TREE_VALUE (pack) == NULL_TREE)
12284 	    continue;
12285 
12286           template_parm_level_and_index (parm, &level, &idx);
12287 
12288           /* Update the corresponding argument.  */
12289           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
12290             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
12291               TREE_TYPE (pack);
12292           else
12293             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
12294         }
12295     }
12296 
12297   if (need_local_specializations)
12298     {
12299       delete local_specializations;
12300       local_specializations = saved_local_specializations;
12301     }
12302 
12303   /* If the dependent pack arguments were such that we end up with only a
12304      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
12305   if (len == 1 && TREE_CODE (result) == TREE_VEC
12306       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
12307     return TREE_VEC_ELT (result, 0);
12308 
12309   return result;
12310 }
12311 
12312 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
12313    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
12314    parameter packs; all parms generated from a function parameter pack will
12315    have the same DECL_PARM_INDEX.  */
12316 
12317 tree
12318 get_pattern_parm (tree parm, tree tmpl)
12319 {
12320   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
12321   tree patparm;
12322 
12323   if (DECL_ARTIFICIAL (parm))
12324     {
12325       for (patparm = DECL_ARGUMENTS (pattern);
12326 	   patparm; patparm = DECL_CHAIN (patparm))
12327 	if (DECL_ARTIFICIAL (patparm)
12328 	    && DECL_NAME (parm) == DECL_NAME (patparm))
12329 	  break;
12330     }
12331   else
12332     {
12333       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
12334       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
12335       gcc_assert (DECL_PARM_INDEX (patparm)
12336 		  == DECL_PARM_INDEX (parm));
12337     }
12338 
12339   return patparm;
12340 }
12341 
12342 /* Make an argument pack out of the TREE_VEC VEC.  */
12343 
12344 static tree
12345 make_argument_pack (tree vec)
12346 {
12347   tree pack;
12348   tree elt = TREE_VEC_ELT (vec, 0);
12349   if (TYPE_P (elt))
12350     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
12351   else
12352     {
12353       pack = make_node (NONTYPE_ARGUMENT_PACK);
12354       TREE_CONSTANT (pack) = 1;
12355     }
12356   SET_ARGUMENT_PACK_ARGS (pack, vec);
12357   return pack;
12358 }
12359 
12360 /* Return an exact copy of template args T that can be modified
12361    independently.  */
12362 
12363 static tree
12364 copy_template_args (tree t)
12365 {
12366   if (t == error_mark_node)
12367     return t;
12368 
12369   int len = TREE_VEC_LENGTH (t);
12370   tree new_vec = make_tree_vec (len);
12371 
12372   for (int i = 0; i < len; ++i)
12373     {
12374       tree elt = TREE_VEC_ELT (t, i);
12375       if (elt && TREE_CODE (elt) == TREE_VEC)
12376 	elt = copy_template_args (elt);
12377       TREE_VEC_ELT (new_vec, i) = elt;
12378     }
12379 
12380   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
12381     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
12382 
12383   return new_vec;
12384 }
12385 
12386 /* Substitute ARGS into the vector or list of template arguments T.  */
12387 
12388 static tree
12389 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12390 {
12391   tree orig_t = t;
12392   int len, need_new = 0, i, expanded_len_adjust = 0, out;
12393   tree *elts;
12394 
12395   if (t == error_mark_node)
12396     return error_mark_node;
12397 
12398   len = TREE_VEC_LENGTH (t);
12399   elts = XALLOCAVEC (tree, len);
12400 
12401   for (i = 0; i < len; i++)
12402     {
12403       tree orig_arg = TREE_VEC_ELT (t, i);
12404       tree new_arg;
12405 
12406       if (TREE_CODE (orig_arg) == TREE_VEC)
12407 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
12408       else if (PACK_EXPANSION_P (orig_arg))
12409         {
12410           /* Substitute into an expansion expression.  */
12411           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
12412 
12413           if (TREE_CODE (new_arg) == TREE_VEC)
12414             /* Add to the expanded length adjustment the number of
12415                expanded arguments. We subtract one from this
12416                measurement, because the argument pack expression
12417                itself is already counted as 1 in
12418                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
12419                the argument pack is empty.  */
12420             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
12421         }
12422       else if (ARGUMENT_PACK_P (orig_arg))
12423         {
12424           /* Substitute into each of the arguments.  */
12425           new_arg = TYPE_P (orig_arg)
12426             ? cxx_make_type (TREE_CODE (orig_arg))
12427             : make_node (TREE_CODE (orig_arg));
12428 
12429 	  tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
12430 						 args, complain, in_decl);
12431           if (pack_args == error_mark_node)
12432             new_arg = error_mark_node;
12433 	  else
12434 	    SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
12435 
12436           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK)
12437 	    TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
12438         }
12439       else
12440 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
12441 
12442       if (new_arg == error_mark_node)
12443 	return error_mark_node;
12444 
12445       elts[i] = new_arg;
12446       if (new_arg != orig_arg)
12447 	need_new = 1;
12448     }
12449 
12450   if (!need_new)
12451     return t;
12452 
12453   /* Make space for the expanded arguments coming from template
12454      argument packs.  */
12455   t = make_tree_vec (len + expanded_len_adjust);
12456   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
12457      arguments for a member template.
12458      In that case each TREE_VEC in ORIG_T represents a level of template
12459      arguments, and ORIG_T won't carry any non defaulted argument count.
12460      It will rather be the nested TREE_VECs that will carry one.
12461      In other words, ORIG_T carries a non defaulted argument count only
12462      if it doesn't contain any nested TREE_VEC.  */
12463   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
12464     {
12465       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
12466       count += expanded_len_adjust;
12467       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
12468     }
12469   for (i = 0, out = 0; i < len; i++)
12470     {
12471       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
12472            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
12473           && TREE_CODE (elts[i]) == TREE_VEC)
12474         {
12475           int idx;
12476 
12477           /* Now expand the template argument pack "in place".  */
12478           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
12479             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
12480         }
12481       else
12482         {
12483           TREE_VEC_ELT (t, out) = elts[i];
12484           out++;
12485         }
12486     }
12487 
12488   return t;
12489 }
12490 
12491 /* Substitute ARGS into one level PARMS of template parameters.  */
12492 
12493 static tree
12494 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
12495 {
12496   if (parms == error_mark_node)
12497     return error_mark_node;
12498 
12499   tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
12500 
12501   for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
12502     {
12503       tree tuple = TREE_VEC_ELT (parms, i);
12504 
12505       if (tuple == error_mark_node)
12506 	continue;
12507 
12508       TREE_VEC_ELT (new_vec, i) =
12509 	tsubst_template_parm (tuple, args, complain);
12510     }
12511 
12512   return new_vec;
12513 }
12514 
12515 /* Return the result of substituting ARGS into the template parameters
12516    given by PARMS.  If there are m levels of ARGS and m + n levels of
12517    PARMS, then the result will contain n levels of PARMS.  For
12518    example, if PARMS is `template <class T> template <class U>
12519    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
12520    result will be `template <int*, double, class V>'.  */
12521 
12522 static tree
12523 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
12524 {
12525   tree r = NULL_TREE;
12526   tree* new_parms;
12527 
12528   /* When substituting into a template, we must set
12529      PROCESSING_TEMPLATE_DECL as the template parameters may be
12530      dependent if they are based on one-another, and the dependency
12531      predicates are short-circuit outside of templates.  */
12532   ++processing_template_decl;
12533 
12534   for (new_parms = &r;
12535        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
12536        new_parms = &(TREE_CHAIN (*new_parms)),
12537 	 parms = TREE_CHAIN (parms))
12538     {
12539       tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
12540 						  args, complain);
12541       *new_parms =
12542 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
12543 			     - TMPL_ARGS_DEPTH (args)),
12544 		   new_vec, NULL_TREE);
12545     }
12546 
12547   --processing_template_decl;
12548 
12549   return r;
12550 }
12551 
12552 /* Return the result of substituting ARGS into one template parameter
12553    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
12554    parameter and which TREE_PURPOSE is the default argument of the
12555    template parameter.  */
12556 
12557 static tree
12558 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
12559 {
12560   tree default_value, parm_decl;
12561 
12562   if (args == NULL_TREE
12563       || t == NULL_TREE
12564       || t == error_mark_node)
12565     return t;
12566 
12567   gcc_assert (TREE_CODE (t) == TREE_LIST);
12568 
12569   default_value = TREE_PURPOSE (t);
12570   parm_decl = TREE_VALUE (t);
12571 
12572   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
12573   if (TREE_CODE (parm_decl) == PARM_DECL
12574       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
12575     parm_decl = error_mark_node;
12576   default_value = tsubst_template_arg (default_value, args,
12577 				       complain, NULL_TREE);
12578 
12579   return build_tree_list (default_value, parm_decl);
12580 }
12581 
12582 /* Substitute the ARGS into the indicated aggregate (or enumeration)
12583    type T.  If T is not an aggregate or enumeration type, it is
12584    handled as if by tsubst.  IN_DECL is as for tsubst.  If
12585    ENTERING_SCOPE is nonzero, T is the context for a template which
12586    we are presently tsubst'ing.  Return the substituted value.  */
12587 
12588 static tree
12589 tsubst_aggr_type (tree t,
12590 		  tree args,
12591 		  tsubst_flags_t complain,
12592 		  tree in_decl,
12593 		  int entering_scope)
12594 {
12595   if (t == NULL_TREE)
12596     return NULL_TREE;
12597 
12598   switch (TREE_CODE (t))
12599     {
12600     case RECORD_TYPE:
12601       if (TYPE_PTRMEMFUNC_P (t))
12602 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
12603 
12604       /* Fall through.  */
12605     case ENUMERAL_TYPE:
12606     case UNION_TYPE:
12607       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
12608 	{
12609 	  tree argvec;
12610 	  tree context;
12611 	  tree r;
12612 	  int saved_unevaluated_operand;
12613 	  int saved_inhibit_evaluation_warnings;
12614 
12615 	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
12616 	  saved_unevaluated_operand = cp_unevaluated_operand;
12617 	  cp_unevaluated_operand = 0;
12618 	  saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12619 	  c_inhibit_evaluation_warnings = 0;
12620 
12621 	  /* First, determine the context for the type we are looking
12622 	     up.  */
12623 	  context = TYPE_CONTEXT (t);
12624 	  if (context && TYPE_P (context))
12625 	    {
12626 	      context = tsubst_aggr_type (context, args, complain,
12627 					  in_decl, /*entering_scope=*/1);
12628 	      /* If context is a nested class inside a class template,
12629 	         it may still need to be instantiated (c++/33959).  */
12630 	      context = complete_type (context);
12631 	    }
12632 
12633 	  /* Then, figure out what arguments are appropriate for the
12634 	     type we are trying to find.  For example, given:
12635 
12636 	       template <class T> struct S;
12637 	       template <class T, class U> void f(T, U) { S<U> su; }
12638 
12639 	     and supposing that we are instantiating f<int, double>,
12640 	     then our ARGS will be {int, double}, but, when looking up
12641 	     S we only want {double}.  */
12642 	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
12643 					 complain, in_decl);
12644 	  if (argvec == error_mark_node)
12645 	    r = error_mark_node;
12646 	  else
12647 	    {
12648 	      r = lookup_template_class (t, argvec, in_decl, context,
12649 					 entering_scope, complain);
12650 	      r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
12651 	    }
12652 
12653 	  cp_unevaluated_operand = saved_unevaluated_operand;
12654 	  c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12655 
12656 	  return r;
12657 	}
12658       else
12659 	/* This is not a template type, so there's nothing to do.  */
12660 	return t;
12661 
12662     default:
12663       return tsubst (t, args, complain, in_decl);
12664     }
12665 }
12666 
12667 static GTY((cache)) tree_cache_map *defarg_inst;
12668 
12669 /* Substitute into the default argument ARG (a default argument for
12670    FN), which has the indicated TYPE.  */
12671 
12672 tree
12673 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
12674 			 tsubst_flags_t complain)
12675 {
12676   tree saved_class_ptr = NULL_TREE;
12677   tree saved_class_ref = NULL_TREE;
12678   int errs = errorcount + sorrycount;
12679 
12680   /* This can happen in invalid code.  */
12681   if (TREE_CODE (arg) == DEFAULT_ARG)
12682     return arg;
12683 
12684   tree parm = FUNCTION_FIRST_USER_PARM (fn);
12685   parm = chain_index (parmnum, parm);
12686   tree parmtype = TREE_TYPE (parm);
12687   if (DECL_BY_REFERENCE (parm))
12688     parmtype = TREE_TYPE (parmtype);
12689   if (parmtype == error_mark_node)
12690     return error_mark_node;
12691 
12692   gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
12693 
12694   tree *slot;
12695   if (defarg_inst && (slot = defarg_inst->get (parm)))
12696     return *slot;
12697 
12698   /* This default argument came from a template.  Instantiate the
12699      default argument here, not in tsubst.  In the case of
12700      something like:
12701 
12702        template <class T>
12703        struct S {
12704 	 static T t();
12705 	 void f(T = t());
12706        };
12707 
12708      we must be careful to do name lookup in the scope of S<T>,
12709      rather than in the current class.  */
12710   push_access_scope (fn);
12711   /* The "this" pointer is not valid in a default argument.  */
12712   if (cfun)
12713     {
12714       saved_class_ptr = current_class_ptr;
12715       cp_function_chain->x_current_class_ptr = NULL_TREE;
12716       saved_class_ref = current_class_ref;
12717       cp_function_chain->x_current_class_ref = NULL_TREE;
12718     }
12719 
12720   start_lambda_scope (parm);
12721 
12722   push_deferring_access_checks(dk_no_deferred);
12723   /* The default argument expression may cause implicitly defined
12724      member functions to be synthesized, which will result in garbage
12725      collection.  We must treat this situation as if we were within
12726      the body of function so as to avoid collecting live data on the
12727      stack.  */
12728   ++function_depth;
12729   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
12730 		     complain, NULL_TREE,
12731 		     /*integral_constant_expression_p=*/false);
12732   --function_depth;
12733   pop_deferring_access_checks();
12734 
12735   finish_lambda_scope ();
12736 
12737   /* Restore the "this" pointer.  */
12738   if (cfun)
12739     {
12740       cp_function_chain->x_current_class_ptr = saved_class_ptr;
12741       cp_function_chain->x_current_class_ref = saved_class_ref;
12742     }
12743 
12744   if (errorcount+sorrycount > errs
12745       && (complain & tf_warning_or_error))
12746     inform (input_location,
12747 	    "  when instantiating default argument for call to %qD", fn);
12748 
12749   /* Make sure the default argument is reasonable.  */
12750   arg = check_default_argument (type, arg, complain);
12751 
12752   pop_access_scope (fn);
12753 
12754   if (arg != error_mark_node && !cp_unevaluated_operand)
12755     {
12756       if (!defarg_inst)
12757 	defarg_inst = tree_cache_map::create_ggc (37);
12758       defarg_inst->put (parm, arg);
12759     }
12760 
12761   return arg;
12762 }
12763 
12764 /* Substitute into all the default arguments for FN.  */
12765 
12766 static void
12767 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
12768 {
12769   tree arg;
12770   tree tmpl_args;
12771 
12772   tmpl_args = DECL_TI_ARGS (fn);
12773 
12774   /* If this function is not yet instantiated, we certainly don't need
12775      its default arguments.  */
12776   if (uses_template_parms (tmpl_args))
12777     return;
12778   /* Don't do this again for clones.  */
12779   if (DECL_CLONED_FUNCTION_P (fn))
12780     return;
12781 
12782   int i = 0;
12783   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
12784        arg;
12785        arg = TREE_CHAIN (arg), ++i)
12786     if (TREE_PURPOSE (arg))
12787       TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
12788 						    TREE_VALUE (arg),
12789 						    TREE_PURPOSE (arg),
12790 						    complain);
12791 }
12792 
12793 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
12794 
12795 static tree
12796 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
12797 		      tree lambda_fntype)
12798 {
12799   tree gen_tmpl, argvec;
12800   hashval_t hash = 0;
12801   tree in_decl = t;
12802 
12803   /* Nobody should be tsubst'ing into non-template functions.  */
12804   gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
12805 
12806   if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
12807     {
12808       /* If T is not dependent, just return it.  */
12809       if (!uses_template_parms (DECL_TI_ARGS (t)))
12810 	return t;
12811 
12812       /* Calculate the most general template of which R is a
12813 	 specialization.  */
12814       gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
12815 
12816       /* We're substituting a lambda function under tsubst_lambda_expr but not
12817 	 directly from it; find the matching function we're already inside.
12818 	 But don't do this if T is a generic lambda with a single level of
12819 	 template parms, as in that case we're doing a normal instantiation. */
12820       if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
12821 	  && (!generic_lambda_fn_p (t)
12822 	      || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
12823 	return enclosing_instantiation_of (t);
12824 
12825       /* Calculate the complete set of arguments used to
12826 	 specialize R.  */
12827       argvec = tsubst_template_args (DECL_TI_ARGS
12828 				     (DECL_TEMPLATE_RESULT
12829 				      (DECL_TI_TEMPLATE (t))),
12830 				     args, complain, in_decl);
12831       if (argvec == error_mark_node)
12832 	return error_mark_node;
12833 
12834       /* Check to see if we already have this specialization.  */
12835       if (!lambda_fntype)
12836 	{
12837 	  hash = hash_tmpl_and_args (gen_tmpl, argvec);
12838 	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
12839 	    return spec;
12840 	}
12841 
12842       /* We can see more levels of arguments than parameters if
12843 	 there was a specialization of a member template, like
12844 	 this:
12845 
12846 	 template <class T> struct S { template <class U> void f(); }
12847 	 template <> template <class U> void S<int>::f(U);
12848 
12849 	 Here, we'll be substituting into the specialization,
12850 	 because that's where we can find the code we actually
12851 	 want to generate, but we'll have enough arguments for
12852 	 the most general template.
12853 
12854 	 We also deal with the peculiar case:
12855 
12856 	 template <class T> struct S {
12857 	   template <class U> friend void f();
12858 	 };
12859 	 template <class U> void f() {}
12860 	 template S<int>;
12861 	 template void f<double>();
12862 
12863 	 Here, the ARGS for the instantiation of will be {int,
12864 	 double}.  But, we only need as many ARGS as there are
12865 	 levels of template parameters in CODE_PATTERN.  We are
12866 	 careful not to get fooled into reducing the ARGS in
12867 	 situations like:
12868 
12869 	 template <class T> struct S { template <class U> void f(U); }
12870 	 template <class T> template <> void S<T>::f(int) {}
12871 
12872 	 which we can spot because the pattern will be a
12873 	 specialization in this case.  */
12874       int args_depth = TMPL_ARGS_DEPTH (args);
12875       int parms_depth =
12876 	TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
12877 
12878       if (args_depth > parms_depth && !DECL_TEMPLATE_SPECIALIZATION (t))
12879 	args = get_innermost_template_args (args, parms_depth);
12880     }
12881   else
12882     {
12883       /* This special case arises when we have something like this:
12884 
12885 	 template <class T> struct S {
12886 	 friend void f<int>(int, double);
12887 	 };
12888 
12889 	 Here, the DECL_TI_TEMPLATE for the friend declaration
12890 	 will be an IDENTIFIER_NODE.  We are being called from
12891 	 tsubst_friend_function, and we want only to create a
12892 	 new decl (R) with appropriate types so that we can call
12893 	 determine_specialization.  */
12894       gen_tmpl = NULL_TREE;
12895       argvec = NULL_TREE;
12896     }
12897 
12898   tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
12899 		  : NULL_TREE);
12900   tree ctx = closure ? closure : DECL_CONTEXT (t);
12901   bool member = ctx && TYPE_P (ctx);
12902 
12903   if (member && !closure)
12904     ctx = tsubst_aggr_type (ctx, args,
12905 			    complain, t, /*entering_scope=*/1);
12906 
12907   tree type = (lambda_fntype ? lambda_fntype
12908 	       : tsubst (TREE_TYPE (t), args,
12909 			 complain | tf_fndecl_type, in_decl));
12910   if (type == error_mark_node)
12911     return error_mark_node;
12912 
12913   /* If we hit excessive deduction depth, the type is bogus even if
12914      it isn't error_mark_node, so don't build a decl.  */
12915   if (excessive_deduction_depth)
12916     return error_mark_node;
12917 
12918   /* We do NOT check for matching decls pushed separately at this
12919      point, as they may not represent instantiations of this
12920      template, and in any case are considered separate under the
12921      discrete model.  */
12922   tree r = copy_decl (t);
12923   DECL_USE_TEMPLATE (r) = 0;
12924   TREE_TYPE (r) = type;
12925   /* Clear out the mangled name and RTL for the instantiation.  */
12926   SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
12927   SET_DECL_RTL (r, NULL);
12928   /* Leave DECL_INITIAL set on deleted instantiations.  */
12929   if (!DECL_DELETED_FN (r))
12930     DECL_INITIAL (r) = NULL_TREE;
12931   DECL_CONTEXT (r) = ctx;
12932 
12933   /* OpenMP UDRs have the only argument a reference to the declared
12934      type.  We want to diagnose if the declared type is a reference,
12935      which is invalid, but as references to references are usually
12936      quietly merged, diagnose it here.  */
12937   if (DECL_OMP_DECLARE_REDUCTION_P (t))
12938     {
12939       tree argtype
12940 	= TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
12941       argtype = tsubst (argtype, args, complain, in_decl);
12942       if (TREE_CODE (argtype) == REFERENCE_TYPE)
12943 	error_at (DECL_SOURCE_LOCATION (t),
12944 		  "reference type %qT in "
12945 		  "%<#pragma omp declare reduction%>", argtype);
12946       if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
12947 	DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
12948 					  argtype);
12949     }
12950 
12951   if (member && DECL_CONV_FN_P (r))
12952     /* Type-conversion operator.  Reconstruct the name, in
12953        case it's the name of one of the template's parameters.  */
12954     DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
12955 
12956   tree parms = DECL_ARGUMENTS (t);
12957   if (closure)
12958     parms = DECL_CHAIN (parms);
12959   parms = tsubst (parms, args, complain, t);
12960   for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
12961     DECL_CONTEXT (parm) = r;
12962   if (closure)
12963     {
12964       tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
12965       DECL_CHAIN (tparm) = parms;
12966       parms = tparm;
12967     }
12968   DECL_ARGUMENTS (r) = parms;
12969   DECL_RESULT (r) = NULL_TREE;
12970 
12971   TREE_STATIC (r) = 0;
12972   TREE_PUBLIC (r) = TREE_PUBLIC (t);
12973   DECL_EXTERNAL (r) = 1;
12974   /* If this is an instantiation of a function with internal
12975      linkage, we already know what object file linkage will be
12976      assigned to the instantiation.  */
12977   DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
12978   DECL_DEFER_OUTPUT (r) = 0;
12979   DECL_CHAIN (r) = NULL_TREE;
12980   DECL_PENDING_INLINE_INFO (r) = 0;
12981   DECL_PENDING_INLINE_P (r) = 0;
12982   DECL_SAVED_TREE (r) = NULL_TREE;
12983   DECL_STRUCT_FUNCTION (r) = NULL;
12984   TREE_USED (r) = 0;
12985   /* We'll re-clone as appropriate in instantiate_template.  */
12986   DECL_CLONED_FUNCTION (r) = NULL_TREE;
12987 
12988   /* If we aren't complaining now, return on error before we register
12989      the specialization so that we'll complain eventually.  */
12990   if ((complain & tf_error) == 0
12991       && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
12992       && !grok_op_properties (r, /*complain=*/false))
12993     return error_mark_node;
12994 
12995   /* When instantiating a constrained member, substitute
12996      into the constraints to create a new constraint.  */
12997   if (tree ci = get_constraints (t))
12998     if (member)
12999       {
13000 	ci = tsubst_constraint_info (ci, argvec, complain, NULL_TREE);
13001 	set_constraints (r, ci);
13002       }
13003 
13004   /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
13005      this in the special friend case mentioned above where
13006      GEN_TMPL is NULL.  */
13007   if (gen_tmpl && !closure)
13008     {
13009       DECL_TEMPLATE_INFO (r)
13010 	= build_template_info (gen_tmpl, argvec);
13011       SET_DECL_IMPLICIT_INSTANTIATION (r);
13012 
13013       tree new_r
13014 	= register_specialization (r, gen_tmpl, argvec, false, hash);
13015       if (new_r != r)
13016 	/* We instantiated this while substituting into
13017 	   the type earlier (template/friend54.C).  */
13018 	return new_r;
13019 
13020       /* We're not supposed to instantiate default arguments
13021 	 until they are called, for a template.  But, for a
13022 	 declaration like:
13023 
13024 	 template <class T> void f ()
13025 	 { extern void g(int i = T()); }
13026 
13027 	 we should do the substitution when the template is
13028 	 instantiated.  We handle the member function case in
13029 	 instantiate_class_template since the default arguments
13030 	 might refer to other members of the class.  */
13031       if (!member
13032 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
13033 	  && !uses_template_parms (argvec))
13034 	tsubst_default_arguments (r, complain);
13035     }
13036   else
13037     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13038 
13039   /* Copy the list of befriending classes.  */
13040   for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
13041        *friends;
13042        friends = &TREE_CHAIN (*friends))
13043     {
13044       *friends = copy_node (*friends);
13045       TREE_VALUE (*friends)
13046 	= tsubst (TREE_VALUE (*friends), args, complain, in_decl);
13047     }
13048 
13049   if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
13050     {
13051       maybe_retrofit_in_chrg (r);
13052       if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
13053 	return error_mark_node;
13054       /* If this is an instantiation of a member template, clone it.
13055 	 If it isn't, that'll be handled by
13056 	 clone_constructors_and_destructors.  */
13057       if (PRIMARY_TEMPLATE_P (gen_tmpl))
13058 	clone_function_decl (r, /*update_methods=*/false);
13059     }
13060   else if ((complain & tf_error) != 0
13061 	   && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13062 	   && !grok_op_properties (r, /*complain=*/true))
13063     return error_mark_node;
13064 
13065   if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
13066     SET_DECL_FRIEND_CONTEXT (r,
13067 			     tsubst (DECL_FRIEND_CONTEXT (t),
13068 				     args, complain, in_decl));
13069 
13070   /* Possibly limit visibility based on template args.  */
13071   DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13072   if (DECL_VISIBILITY_SPECIFIED (t))
13073     {
13074       DECL_VISIBILITY_SPECIFIED (r) = 0;
13075       DECL_ATTRIBUTES (r)
13076 	= remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13077     }
13078   determine_visibility (r);
13079   if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
13080       && !processing_template_decl)
13081     defaulted_late_check (r);
13082 
13083   apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13084 				  args, complain, in_decl);
13085   return r;
13086 }
13087 
13088 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
13089 
13090 static tree
13091 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
13092 		      tree lambda_fntype)
13093 {
13094   /* We can get here when processing a member function template,
13095      member class template, or template template parameter.  */
13096   tree decl = DECL_TEMPLATE_RESULT (t);
13097   tree in_decl = t;
13098   tree spec;
13099   tree tmpl_args;
13100   tree full_args;
13101   tree r;
13102   hashval_t hash = 0;
13103 
13104   if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
13105     {
13106       /* Template template parameter is treated here.  */
13107       tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13108       if (new_type == error_mark_node)
13109 	r = error_mark_node;
13110       /* If we get a real template back, return it.  This can happen in
13111 	 the context of most_specialized_partial_spec.  */
13112       else if (TREE_CODE (new_type) == TEMPLATE_DECL)
13113 	r = new_type;
13114       else
13115 	/* The new TEMPLATE_DECL was built in
13116 	   reduce_template_parm_level.  */
13117 	r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
13118       return r;
13119     }
13120 
13121   if (!lambda_fntype)
13122     {
13123       /* We might already have an instance of this template.
13124 	 The ARGS are for the surrounding class type, so the
13125 	 full args contain the tsubst'd args for the context,
13126 	 plus the innermost args from the template decl.  */
13127       tmpl_args = DECL_CLASS_TEMPLATE_P (t)
13128 	? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
13129 	: DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
13130       /* Because this is a template, the arguments will still be
13131 	 dependent, even after substitution.  If
13132 	 PROCESSING_TEMPLATE_DECL is not set, the dependency
13133 	 predicates will short-circuit.  */
13134       ++processing_template_decl;
13135       full_args = tsubst_template_args (tmpl_args, args,
13136 					complain, in_decl);
13137       --processing_template_decl;
13138       if (full_args == error_mark_node)
13139 	return error_mark_node;
13140 
13141       /* If this is a default template template argument,
13142 	 tsubst might not have changed anything.  */
13143       if (full_args == tmpl_args)
13144 	return t;
13145 
13146       hash = hash_tmpl_and_args (t, full_args);
13147       spec = retrieve_specialization (t, full_args, hash);
13148       if (spec != NULL_TREE)
13149 	return spec;
13150     }
13151 
13152   /* Make a new template decl.  It will be similar to the
13153      original, but will record the current template arguments.
13154      We also create a new function declaration, which is just
13155      like the old one, but points to this new template, rather
13156      than the old one.  */
13157   r = copy_decl (t);
13158   gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
13159   DECL_CHAIN (r) = NULL_TREE;
13160 
13161   // Build new template info linking to the original template decl.
13162   if (!lambda_fntype)
13163     {
13164       DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13165       SET_DECL_IMPLICIT_INSTANTIATION (r);
13166     }
13167   else
13168     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13169 
13170   /* The template parameters for this new template are all the
13171      template parameters for the old template, except the
13172      outermost level of parameters.  */
13173   DECL_TEMPLATE_PARMS (r)
13174     = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
13175 			     complain);
13176 
13177   if (TREE_CODE (decl) == TYPE_DECL
13178       && !TYPE_DECL_ALIAS_P (decl))
13179     {
13180       tree new_type;
13181       ++processing_template_decl;
13182       new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13183       --processing_template_decl;
13184       if (new_type == error_mark_node)
13185 	return error_mark_node;
13186 
13187       TREE_TYPE (r) = new_type;
13188       /* For a partial specialization, we need to keep pointing to
13189 	 the primary template.  */
13190       if (!DECL_TEMPLATE_SPECIALIZATION (t))
13191 	CLASSTYPE_TI_TEMPLATE (new_type) = r;
13192       DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
13193       DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
13194       DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
13195     }
13196   else
13197     {
13198       tree new_decl;
13199       ++processing_template_decl;
13200       if (TREE_CODE (decl) == FUNCTION_DECL)
13201 	new_decl = tsubst_function_decl (decl, args, complain, lambda_fntype);
13202       else
13203 	new_decl = tsubst (decl, args, complain, in_decl);
13204       --processing_template_decl;
13205       if (new_decl == error_mark_node)
13206 	return error_mark_node;
13207 
13208       DECL_TEMPLATE_RESULT (r) = new_decl;
13209       TREE_TYPE (r) = TREE_TYPE (new_decl);
13210       DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
13211       if (lambda_fntype)
13212 	{
13213 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
13214 	  DECL_TEMPLATE_INFO (new_decl) = build_template_info (r, args);
13215 	}
13216       else
13217 	{
13218 	  DECL_TI_TEMPLATE (new_decl) = r;
13219 	  DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
13220 	}
13221     }
13222 
13223   DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
13224   DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
13225 
13226   if (PRIMARY_TEMPLATE_P (t))
13227     DECL_PRIMARY_TEMPLATE (r) = r;
13228 
13229   if (TREE_CODE (decl) != TYPE_DECL && !VAR_P (decl)
13230       && !lambda_fntype)
13231     /* Record this non-type partial instantiation.  */
13232     register_specialization (r, t,
13233 			     DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
13234 			     false, hash);
13235 
13236   return r;
13237 }
13238 
13239 /* True if FN is the op() for a lambda in an uninstantiated template.  */
13240 
13241 bool
13242 lambda_fn_in_template_p (tree fn)
13243 {
13244   if (!fn || !LAMBDA_FUNCTION_P (fn))
13245     return false;
13246   tree closure = DECL_CONTEXT (fn);
13247   return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
13248 }
13249 
13250 /* We're instantiating a variable from template function TCTX.  Return the
13251    corresponding current enclosing scope.  This gets complicated because lambda
13252    functions in templates are regenerated rather than instantiated, but generic
13253    lambda functions are subsequently instantiated.  */
13254 
13255 static tree
13256 enclosing_instantiation_of (tree otctx)
13257 {
13258   tree tctx = otctx;
13259   tree fn = current_function_decl;
13260   int lambda_count = 0;
13261 
13262   for (; tctx && lambda_fn_in_template_p (tctx);
13263        tctx = decl_function_context (tctx))
13264     ++lambda_count;
13265   for (; fn; fn = decl_function_context (fn))
13266     {
13267       tree ofn = fn;
13268       int flambda_count = 0;
13269       for (; flambda_count < lambda_count && fn && LAMBDA_FUNCTION_P (fn);
13270 	   fn = decl_function_context (fn))
13271 	++flambda_count;
13272       if ((fn && DECL_TEMPLATE_INFO (fn))
13273 	  ? most_general_template (fn) != most_general_template (tctx)
13274 	  : fn != tctx)
13275 	continue;
13276       gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
13277 		  || DECL_CONV_FN_P (ofn));
13278       return ofn;
13279     }
13280   gcc_unreachable ();
13281 }
13282 
13283 /* Substitute the ARGS into the T, which is a _DECL.  Return the
13284    result of the substitution.  Issue error and warning messages under
13285    control of COMPLAIN.  */
13286 
13287 static tree
13288 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
13289 {
13290 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
13291   location_t saved_loc;
13292   tree r = NULL_TREE;
13293   tree in_decl = t;
13294   hashval_t hash = 0;
13295 
13296   /* Set the filename and linenumber to improve error-reporting.  */
13297   saved_loc = input_location;
13298   input_location = DECL_SOURCE_LOCATION (t);
13299 
13300   switch (TREE_CODE (t))
13301     {
13302     case TEMPLATE_DECL:
13303       r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
13304       break;
13305 
13306     case FUNCTION_DECL:
13307       r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
13308       break;
13309 
13310     case PARM_DECL:
13311       {
13312 	tree type = NULL_TREE;
13313         int i, len = 1;
13314         tree expanded_types = NULL_TREE;
13315         tree prev_r = NULL_TREE;
13316         tree first_r = NULL_TREE;
13317 
13318         if (DECL_PACK_P (t))
13319           {
13320             /* If there is a local specialization that isn't a
13321                parameter pack, it means that we're doing a "simple"
13322                substitution from inside tsubst_pack_expansion. Just
13323                return the local specialization (which will be a single
13324                parm).  */
13325             tree spec = retrieve_local_specialization (t);
13326             if (spec
13327                 && TREE_CODE (spec) == PARM_DECL
13328                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
13329               RETURN (spec);
13330 
13331             /* Expand the TYPE_PACK_EXPANSION that provides the types for
13332                the parameters in this function parameter pack.  */
13333             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13334 						    complain, in_decl);
13335             if (TREE_CODE (expanded_types) == TREE_VEC)
13336               {
13337                 len = TREE_VEC_LENGTH (expanded_types);
13338 
13339                 /* Zero-length parameter packs are boring. Just substitute
13340                    into the chain.  */
13341                 if (len == 0)
13342                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
13343 				  TREE_CHAIN (t)));
13344               }
13345             else
13346               {
13347                 /* All we did was update the type. Make a note of that.  */
13348                 type = expanded_types;
13349                 expanded_types = NULL_TREE;
13350               }
13351           }
13352 
13353         /* Loop through all of the parameters we'll build. When T is
13354            a function parameter pack, LEN is the number of expanded
13355            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
13356         r = NULL_TREE;
13357         for (i = 0; i < len; ++i)
13358           {
13359             prev_r = r;
13360             r = copy_node (t);
13361             if (DECL_TEMPLATE_PARM_P (t))
13362               SET_DECL_TEMPLATE_PARM_P (r);
13363 
13364             if (expanded_types)
13365               /* We're on the Ith parameter of the function parameter
13366                  pack.  */
13367               {
13368                 /* Get the Ith type.  */
13369                 type = TREE_VEC_ELT (expanded_types, i);
13370 
13371 		/* Rename the parameter to include the index.  */
13372 		DECL_NAME (r)
13373 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
13374               }
13375             else if (!type)
13376               /* We're dealing with a normal parameter.  */
13377               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13378 
13379             type = type_decays_to (type);
13380             TREE_TYPE (r) = type;
13381             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13382 
13383             if (DECL_INITIAL (r))
13384               {
13385                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
13386                   DECL_INITIAL (r) = TREE_TYPE (r);
13387                 else
13388                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
13389                                              complain, in_decl);
13390               }
13391 
13392             DECL_CONTEXT (r) = NULL_TREE;
13393 
13394             if (!DECL_TEMPLATE_PARM_P (r))
13395               DECL_ARG_TYPE (r) = type_passed_as (type);
13396 
13397 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13398 					    args, complain, in_decl);
13399 
13400             /* Keep track of the first new parameter we
13401                generate. That's what will be returned to the
13402                caller.  */
13403             if (!first_r)
13404               first_r = r;
13405 
13406             /* Build a proper chain of parameters when substituting
13407                into a function parameter pack.  */
13408             if (prev_r)
13409               DECL_CHAIN (prev_r) = r;
13410           }
13411 
13412 	/* If cp_unevaluated_operand is set, we're just looking for a
13413 	   single dummy parameter, so don't keep going.  */
13414 	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
13415 	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
13416 				   complain, DECL_CHAIN (t));
13417 
13418         /* FIRST_R contains the start of the chain we've built.  */
13419         r = first_r;
13420       }
13421       break;
13422 
13423     case FIELD_DECL:
13424       {
13425 	tree type = NULL_TREE;
13426 	tree vec = NULL_TREE;
13427 	tree expanded_types = NULL_TREE;
13428 	int len = 1;
13429 
13430 	if (PACK_EXPANSION_P (TREE_TYPE (t)))
13431 	  {
13432 	    /* This field is a lambda capture pack.  Return a TREE_VEC of
13433 	       the expanded fields to instantiate_class_template_1.  */
13434             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13435 						    complain, in_decl);
13436             if (TREE_CODE (expanded_types) == TREE_VEC)
13437               {
13438                 len = TREE_VEC_LENGTH (expanded_types);
13439 		vec = make_tree_vec (len);
13440               }
13441             else
13442               {
13443                 /* All we did was update the type. Make a note of that.  */
13444                 type = expanded_types;
13445                 expanded_types = NULL_TREE;
13446               }
13447 	  }
13448 
13449 	for (int i = 0; i < len; ++i)
13450 	  {
13451 	    r = copy_decl (t);
13452 	    if (expanded_types)
13453 	      {
13454 		type = TREE_VEC_ELT (expanded_types, i);
13455 		DECL_NAME (r)
13456 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
13457 	      }
13458             else if (!type)
13459               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13460 
13461 	    if (type == error_mark_node)
13462 	      RETURN (error_mark_node);
13463 	    TREE_TYPE (r) = type;
13464 	    cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13465 
13466 	    if (DECL_C_BIT_FIELD (r))
13467 	      /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
13468 		 number of bits.  */
13469 	      DECL_BIT_FIELD_REPRESENTATIVE (r)
13470 		= tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
13471 			       complain, in_decl,
13472 			       /*integral_constant_expression_p=*/true);
13473 	    if (DECL_INITIAL (t))
13474 	      {
13475 		/* Set up DECL_TEMPLATE_INFO so that we can get at the
13476 		   NSDMI in perform_member_init.  Still set DECL_INITIAL
13477 		   so that we know there is one.  */
13478 		DECL_INITIAL (r) = void_node;
13479 		gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
13480 		retrofit_lang_decl (r);
13481 		DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13482 	      }
13483 	    /* We don't have to set DECL_CONTEXT here; it is set by
13484 	       finish_member_declaration.  */
13485 	    DECL_CHAIN (r) = NULL_TREE;
13486 
13487 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13488 					    args, complain, in_decl);
13489 
13490 	    if (vec)
13491 	      TREE_VEC_ELT (vec, i) = r;
13492 	  }
13493 
13494 	if (vec)
13495 	  r = vec;
13496       }
13497       break;
13498 
13499     case USING_DECL:
13500       /* We reach here only for member using decls.  We also need to check
13501 	 uses_template_parms because DECL_DEPENDENT_P is not set for a
13502 	 using-declaration that designates a member of the current
13503 	 instantiation (c++/53549).  */
13504       if (DECL_DEPENDENT_P (t)
13505 	  || uses_template_parms (USING_DECL_SCOPE (t)))
13506 	{
13507 	  tree scope = USING_DECL_SCOPE (t);
13508 	  tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
13509 	  if (PACK_EXPANSION_P (scope))
13510 	    {
13511 	      tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
13512 	      int len = TREE_VEC_LENGTH (vec);
13513 	      r = make_tree_vec (len);
13514 	      for (int i = 0; i < len; ++i)
13515 		{
13516 		  tree escope = TREE_VEC_ELT (vec, i);
13517 		  tree elt = do_class_using_decl (escope, name);
13518 		  if (!elt)
13519 		    {
13520 		      r = error_mark_node;
13521 		      break;
13522 		    }
13523 		  else
13524 		    {
13525 		      TREE_PROTECTED (elt) = TREE_PROTECTED (t);
13526 		      TREE_PRIVATE (elt) = TREE_PRIVATE (t);
13527 		    }
13528 		  TREE_VEC_ELT (r, i) = elt;
13529 		}
13530 	    }
13531 	  else
13532 	    {
13533 	      tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
13534 					     complain, in_decl);
13535 	      r = do_class_using_decl (inst_scope, name);
13536 	      if (!r)
13537 		r = error_mark_node;
13538 	      else
13539 		{
13540 		  TREE_PROTECTED (r) = TREE_PROTECTED (t);
13541 		  TREE_PRIVATE (r) = TREE_PRIVATE (t);
13542 		}
13543 	    }
13544 	}
13545       else
13546 	{
13547 	  r = copy_node (t);
13548 	  DECL_CHAIN (r) = NULL_TREE;
13549 	}
13550       break;
13551 
13552     case TYPE_DECL:
13553     case VAR_DECL:
13554       {
13555 	tree argvec = NULL_TREE;
13556 	tree gen_tmpl = NULL_TREE;
13557 	tree spec;
13558 	tree tmpl = NULL_TREE;
13559 	tree ctx;
13560 	tree type = NULL_TREE;
13561 	bool local_p;
13562 
13563 	if (TREE_TYPE (t) == error_mark_node)
13564 	  RETURN (error_mark_node);
13565 
13566 	if (TREE_CODE (t) == TYPE_DECL
13567 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
13568 	  {
13569 	    /* If this is the canonical decl, we don't have to
13570 	       mess with instantiations, and often we can't (for
13571 	       typename, template type parms and such).  Note that
13572 	       TYPE_NAME is not correct for the above test if
13573 	       we've copied the type for a typedef.  */
13574 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13575 	    if (type == error_mark_node)
13576 	      RETURN (error_mark_node);
13577 	    r = TYPE_NAME (type);
13578 	    break;
13579 	  }
13580 
13581 	/* Check to see if we already have the specialization we
13582 	   need.  */
13583 	spec = NULL_TREE;
13584 	if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
13585 	  {
13586 	    /* T is a static data member or namespace-scope entity.
13587 	       We have to substitute into namespace-scope variables
13588 	       (not just variable templates) because of cases like:
13589 
13590 	         template <class T> void f() { extern T t; }
13591 
13592 	       where the entity referenced is not known until
13593 	       instantiation time.  */
13594 	    local_p = false;
13595 	    ctx = DECL_CONTEXT (t);
13596 	    if (DECL_CLASS_SCOPE_P (t))
13597 	      {
13598 		ctx = tsubst_aggr_type (ctx, args,
13599 					complain,
13600 					in_decl, /*entering_scope=*/1);
13601 		/* If CTX is unchanged, then T is in fact the
13602 		   specialization we want.  That situation occurs when
13603 		   referencing a static data member within in its own
13604 		   class.  We can use pointer equality, rather than
13605 		   same_type_p, because DECL_CONTEXT is always
13606 		   canonical...  */
13607 		if (ctx == DECL_CONTEXT (t)
13608 		    /* ... unless T is a member template; in which
13609 		       case our caller can be willing to create a
13610 		       specialization of that template represented
13611 		       by T.  */
13612 		    && !(DECL_TI_TEMPLATE (t)
13613 			 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
13614 		  spec = t;
13615 	      }
13616 
13617 	    if (!spec)
13618 	      {
13619 		tmpl = DECL_TI_TEMPLATE (t);
13620 		gen_tmpl = most_general_template (tmpl);
13621 		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
13622 		if (argvec != error_mark_node)
13623 		  argvec = (coerce_innermost_template_parms
13624 			    (DECL_TEMPLATE_PARMS (gen_tmpl),
13625 			     argvec, t, complain,
13626 			     /*all*/true, /*defarg*/true));
13627 		if (argvec == error_mark_node)
13628 		  RETURN (error_mark_node);
13629 		hash = hash_tmpl_and_args (gen_tmpl, argvec);
13630 		spec = retrieve_specialization (gen_tmpl, argvec, hash);
13631 	      }
13632 	  }
13633 	else
13634 	  {
13635 	    /* A local variable.  */
13636 	    local_p = true;
13637 	    /* Subsequent calls to pushdecl will fill this in.  */
13638 	    ctx = NULL_TREE;
13639 	    /* Unless this is a reference to a static variable from an
13640 	       enclosing function, in which case we need to fill it in now.  */
13641 	    if (TREE_STATIC (t))
13642 	      {
13643 		tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
13644 		if (fn != current_function_decl)
13645 		  ctx = fn;
13646 	      }
13647 	    spec = retrieve_local_specialization (t);
13648 	  }
13649 	/* If we already have the specialization we need, there is
13650 	   nothing more to do.  */
13651 	if (spec)
13652 	  {
13653 	    r = spec;
13654 	    break;
13655 	  }
13656 
13657 	/* Create a new node for the specialization we need.  */
13658 	r = copy_decl (t);
13659 	if (type == NULL_TREE)
13660 	  {
13661 	    if (is_typedef_decl (t))
13662 	      type = DECL_ORIGINAL_TYPE (t);
13663 	    else
13664 	      type = TREE_TYPE (t);
13665 	    if (VAR_P (t)
13666 		&& VAR_HAD_UNKNOWN_BOUND (t)
13667 		&& type != error_mark_node)
13668 	      type = strip_array_domain (type);
13669 	    tree sub_args = args;
13670 	    if (tree auto_node = type_uses_auto (type))
13671 	      {
13672 		/* Mask off any template args past the variable's context so we
13673 		   don't replace the auto with an unrelated argument.  */
13674 		int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
13675 		int extra = TMPL_ARGS_DEPTH (args) - nouter;
13676 		if (extra > 0)
13677 		  /* This should never happen with the new lambda instantiation
13678 		     model, but keep the handling just in case.  */
13679 		  gcc_assert (!CHECKING_P),
13680 		  sub_args = strip_innermost_template_args (args, extra);
13681 	      }
13682 	    type = tsubst (type, sub_args, complain, in_decl);
13683 	  }
13684 	if (VAR_P (r))
13685 	  {
13686 	    /* Even if the original location is out of scope, the
13687 	       newly substituted one is not.  */
13688 	    DECL_DEAD_FOR_LOCAL (r) = 0;
13689 	    DECL_INITIALIZED_P (r) = 0;
13690 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
13691 	    if (type == error_mark_node)
13692 	      RETURN (error_mark_node);
13693 	    if (TREE_CODE (type) == FUNCTION_TYPE)
13694 	      {
13695 		/* It may seem that this case cannot occur, since:
13696 
13697 		   typedef void f();
13698 		   void g() { f x; }
13699 
13700 		   declares a function, not a variable.  However:
13701 
13702 		   typedef void f();
13703 		   template <typename T> void g() { T t; }
13704 		   template void g<f>();
13705 
13706 		   is an attempt to declare a variable with function
13707 		   type.  */
13708 		error ("variable %qD has function type",
13709 		       /* R is not yet sufficiently initialized, so we
13710 			  just use its name.  */
13711 		       DECL_NAME (r));
13712 		RETURN (error_mark_node);
13713 	      }
13714 	    type = complete_type (type);
13715 	    /* Wait until cp_finish_decl to set this again, to handle
13716 	       circular dependency (template/instantiate6.C). */
13717 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
13718 	    type = check_var_type (DECL_NAME (r), type);
13719 
13720 	    if (DECL_HAS_VALUE_EXPR_P (t))
13721 	      {
13722 		tree ve = DECL_VALUE_EXPR (t);
13723 		ve = tsubst_expr (ve, args, complain, in_decl,
13724 				  /*constant_expression_p=*/false);
13725 		if (REFERENCE_REF_P (ve))
13726 		  {
13727 		    gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
13728 		    ve = TREE_OPERAND (ve, 0);
13729 		  }
13730 		SET_DECL_VALUE_EXPR (r, ve);
13731 	      }
13732 	    if (CP_DECL_THREAD_LOCAL_P (r)
13733 		&& !processing_template_decl)
13734 	      set_decl_tls_model (r, decl_default_tls_model (r));
13735 	  }
13736 	else if (DECL_SELF_REFERENCE_P (t))
13737 	  SET_DECL_SELF_REFERENCE_P (r);
13738 	TREE_TYPE (r) = type;
13739 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13740 	DECL_CONTEXT (r) = ctx;
13741 	/* Clear out the mangled name and RTL for the instantiation.  */
13742 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13743 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
13744 	  SET_DECL_RTL (r, NULL);
13745 	/* The initializer must not be expanded until it is required;
13746 	   see [temp.inst].  */
13747 	DECL_INITIAL (r) = NULL_TREE;
13748 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
13749 	if (VAR_P (r))
13750 	  {
13751 	    if (DECL_LANG_SPECIFIC (r))
13752 	      SET_DECL_DEPENDENT_INIT_P (r, false);
13753 
13754 	    SET_DECL_MODE (r, VOIDmode);
13755 
13756 	    /* Possibly limit visibility based on template args.  */
13757 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13758 	    if (DECL_VISIBILITY_SPECIFIED (t))
13759 	      {
13760 		DECL_VISIBILITY_SPECIFIED (r) = 0;
13761 		DECL_ATTRIBUTES (r)
13762 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13763 	      }
13764 	    determine_visibility (r);
13765 	  }
13766 
13767 	if (!local_p)
13768 	  {
13769 	    /* A static data member declaration is always marked
13770 	       external when it is declared in-class, even if an
13771 	       initializer is present.  We mimic the non-template
13772 	       processing here.  */
13773 	    DECL_EXTERNAL (r) = 1;
13774 	    if (DECL_NAMESPACE_SCOPE_P (t))
13775 	      DECL_NOT_REALLY_EXTERN (r) = 1;
13776 
13777 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
13778 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
13779 	    register_specialization (r, gen_tmpl, argvec, false, hash);
13780 	  }
13781 	else
13782 	  {
13783 	    if (DECL_LANG_SPECIFIC (r))
13784 	      DECL_TEMPLATE_INFO (r) = NULL_TREE;
13785 	    if (!cp_unevaluated_operand)
13786 	      register_local_specialization (r, t);
13787 	  }
13788 
13789 	DECL_CHAIN (r) = NULL_TREE;
13790 
13791 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
13792 					/*flags=*/0,
13793 					args, complain, in_decl);
13794 
13795 	/* Preserve a typedef that names a type.  */
13796 	if (is_typedef_decl (r) && type != error_mark_node)
13797 	  {
13798 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
13799 	    set_underlying_type (r);
13800 	    if (TYPE_DECL_ALIAS_P (r))
13801 	      /* An alias template specialization can be dependent
13802 		 even if its underlying type is not.  */
13803 	      TYPE_DEPENDENT_P_VALID (TREE_TYPE (r)) = false;
13804 	  }
13805 
13806 	layout_decl (r, 0);
13807       }
13808       break;
13809 
13810     default:
13811       gcc_unreachable ();
13812     }
13813 #undef RETURN
13814 
13815  out:
13816   /* Restore the file and line information.  */
13817   input_location = saved_loc;
13818 
13819   return r;
13820 }
13821 
13822 /* Substitute into the ARG_TYPES of a function type.
13823    If END is a TREE_CHAIN, leave it and any following types
13824    un-substituted.  */
13825 
13826 static tree
13827 tsubst_arg_types (tree arg_types,
13828 		  tree args,
13829 		  tree end,
13830 		  tsubst_flags_t complain,
13831 		  tree in_decl)
13832 {
13833   tree remaining_arg_types;
13834   tree type = NULL_TREE;
13835   int i = 1;
13836   tree expanded_args = NULL_TREE;
13837   tree default_arg;
13838 
13839   if (!arg_types || arg_types == void_list_node || arg_types == end)
13840     return arg_types;
13841 
13842   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
13843 					  args, end, complain, in_decl);
13844   if (remaining_arg_types == error_mark_node)
13845     return error_mark_node;
13846 
13847   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
13848     {
13849       /* For a pack expansion, perform substitution on the
13850          entire expression. Later on, we'll handle the arguments
13851          one-by-one.  */
13852       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
13853                                             args, complain, in_decl);
13854 
13855       if (TREE_CODE (expanded_args) == TREE_VEC)
13856         /* So that we'll spin through the parameters, one by one.  */
13857         i = TREE_VEC_LENGTH (expanded_args);
13858       else
13859         {
13860           /* We only partially substituted into the parameter
13861              pack. Our type is TYPE_PACK_EXPANSION.  */
13862           type = expanded_args;
13863           expanded_args = NULL_TREE;
13864         }
13865     }
13866 
13867   while (i > 0) {
13868     --i;
13869 
13870     if (expanded_args)
13871       type = TREE_VEC_ELT (expanded_args, i);
13872     else if (!type)
13873       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
13874 
13875     if (type == error_mark_node)
13876       return error_mark_node;
13877     if (VOID_TYPE_P (type))
13878       {
13879         if (complain & tf_error)
13880           {
13881             error ("invalid parameter type %qT", type);
13882             if (in_decl)
13883               error ("in declaration %q+D", in_decl);
13884           }
13885         return error_mark_node;
13886     }
13887     /* DR 657. */
13888     if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
13889       return error_mark_node;
13890 
13891     /* Do array-to-pointer, function-to-pointer conversion, and ignore
13892        top-level qualifiers as required.  */
13893     type = cv_unqualified (type_decays_to (type));
13894 
13895     /* We do not substitute into default arguments here.  The standard
13896        mandates that they be instantiated only when needed, which is
13897        done in build_over_call.  */
13898     default_arg = TREE_PURPOSE (arg_types);
13899 
13900     /* Except that we do substitute default arguments under tsubst_lambda_expr,
13901        since the new op() won't have any associated template arguments for us
13902        to refer to later.  */
13903     if (lambda_fn_in_template_p (in_decl))
13904       default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
13905 					   false/*fn*/, false/*constexpr*/);
13906 
13907     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
13908       {
13909         /* We've instantiated a template before its default arguments
13910            have been parsed.  This can happen for a nested template
13911            class, and is not an error unless we require the default
13912            argument in a call of this function.  */
13913         remaining_arg_types =
13914           tree_cons (default_arg, type, remaining_arg_types);
13915         vec_safe_push (DEFARG_INSTANTIATIONS(default_arg), remaining_arg_types);
13916       }
13917     else
13918       remaining_arg_types =
13919         hash_tree_cons (default_arg, type, remaining_arg_types);
13920   }
13921 
13922   return remaining_arg_types;
13923 }
13924 
13925 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
13926    *not* handle the exception-specification for FNTYPE, because the
13927    initial substitution of explicitly provided template parameters
13928    during argument deduction forbids substitution into the
13929    exception-specification:
13930 
13931      [temp.deduct]
13932 
13933      All references in the function type of the function template to  the
13934      corresponding template parameters are replaced by the specified tem-
13935      plate argument values.  If a substitution in a template parameter or
13936      in  the function type of the function template results in an invalid
13937      type, type deduction fails.  [Note: The equivalent  substitution  in
13938      exception specifications is done only when the function is instanti-
13939      ated, at which point a program is  ill-formed  if  the  substitution
13940      results in an invalid type.]  */
13941 
13942 static tree
13943 tsubst_function_type (tree t,
13944 		      tree args,
13945 		      tsubst_flags_t complain,
13946 		      tree in_decl)
13947 {
13948   tree return_type;
13949   tree arg_types = NULL_TREE;
13950   tree fntype;
13951 
13952   /* The TYPE_CONTEXT is not used for function/method types.  */
13953   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
13954 
13955   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
13956      failure.  */
13957   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
13958 
13959   if (late_return_type_p)
13960     {
13961       /* Substitute the argument types.  */
13962       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
13963 				    complain, in_decl);
13964       if (arg_types == error_mark_node)
13965 	return error_mark_node;
13966 
13967       tree save_ccp = current_class_ptr;
13968       tree save_ccr = current_class_ref;
13969       tree this_type = (TREE_CODE (t) == METHOD_TYPE
13970 			? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
13971       bool do_inject = this_type && CLASS_TYPE_P (this_type);
13972       if (do_inject)
13973 	{
13974 	  /* DR 1207: 'this' is in scope in the trailing return type.  */
13975 	  inject_this_parameter (this_type, cp_type_quals (this_type));
13976 	}
13977 
13978       /* Substitute the return type.  */
13979       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13980 
13981       if (do_inject)
13982 	{
13983 	  current_class_ptr = save_ccp;
13984 	  current_class_ref = save_ccr;
13985 	}
13986     }
13987   else
13988     /* Substitute the return type.  */
13989     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13990 
13991   if (return_type == error_mark_node)
13992     return error_mark_node;
13993   /* DR 486 clarifies that creation of a function type with an
13994      invalid return type is a deduction failure.  */
13995   if (TREE_CODE (return_type) == ARRAY_TYPE
13996       || TREE_CODE (return_type) == FUNCTION_TYPE)
13997     {
13998       if (complain & tf_error)
13999 	{
14000 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
14001 	    error ("function returning an array");
14002 	  else
14003 	    error ("function returning a function");
14004 	}
14005       return error_mark_node;
14006     }
14007   /* And DR 657. */
14008   if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
14009     return error_mark_node;
14010 
14011   if (!late_return_type_p)
14012     {
14013       /* Substitute the argument types.  */
14014       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14015 				    complain, in_decl);
14016       if (arg_types == error_mark_node)
14017 	return error_mark_node;
14018     }
14019 
14020   /* Construct a new type node and return it.  */
14021   if (TREE_CODE (t) == FUNCTION_TYPE)
14022     {
14023       fntype = build_function_type (return_type, arg_types);
14024       fntype = apply_memfn_quals (fntype,
14025 				  type_memfn_quals (t),
14026 				  type_memfn_rqual (t));
14027     }
14028   else
14029     {
14030       tree r = TREE_TYPE (TREE_VALUE (arg_types));
14031       /* Don't pick up extra function qualifiers from the basetype.  */
14032       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
14033       if (! MAYBE_CLASS_TYPE_P (r))
14034 	{
14035 	  /* [temp.deduct]
14036 
14037 	     Type deduction may fail for any of the following
14038 	     reasons:
14039 
14040 	     -- Attempting to create "pointer to member of T" when T
14041 	     is not a class type.  */
14042 	  if (complain & tf_error)
14043 	    error ("creating pointer to member function of non-class type %qT",
14044 		      r);
14045 	  return error_mark_node;
14046 	}
14047 
14048       fntype = build_method_type_directly (r, return_type,
14049 					   TREE_CHAIN (arg_types));
14050       fntype = build_ref_qualified_type (fntype, type_memfn_rqual (t));
14051     }
14052   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
14053 
14054   if (late_return_type_p)
14055     TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1;
14056 
14057   return fntype;
14058 }
14059 
14060 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
14061    ARGS into that specification, and return the substituted
14062    specification.  If there is no specification, return NULL_TREE.  */
14063 
14064 static tree
14065 tsubst_exception_specification (tree fntype,
14066 				tree args,
14067 				tsubst_flags_t complain,
14068 				tree in_decl,
14069 				bool defer_ok)
14070 {
14071   tree specs;
14072   tree new_specs;
14073 
14074   specs = TYPE_RAISES_EXCEPTIONS (fntype);
14075   new_specs = NULL_TREE;
14076   if (specs && TREE_PURPOSE (specs))
14077     {
14078       /* A noexcept-specifier.  */
14079       tree expr = TREE_PURPOSE (specs);
14080       if (TREE_CODE (expr) == INTEGER_CST)
14081 	new_specs = expr;
14082       else if (defer_ok)
14083 	{
14084 	  /* Defer instantiation of noexcept-specifiers to avoid
14085 	     excessive instantiations (c++/49107).  */
14086 	  new_specs = make_node (DEFERRED_NOEXCEPT);
14087 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
14088 	    {
14089 	      /* We already partially instantiated this member template,
14090 		 so combine the new args with the old.  */
14091 	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
14092 		= DEFERRED_NOEXCEPT_PATTERN (expr);
14093 	      DEFERRED_NOEXCEPT_ARGS (new_specs)
14094 		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
14095 	    }
14096 	  else
14097 	    {
14098 	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
14099 	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
14100 	    }
14101 	}
14102       else
14103 	new_specs = tsubst_copy_and_build
14104 	  (expr, args, complain, in_decl, /*function_p=*/false,
14105 	   /*integral_constant_expression_p=*/true);
14106       new_specs = build_noexcept_spec (new_specs, complain);
14107     }
14108   else if (specs)
14109     {
14110       if (! TREE_VALUE (specs))
14111 	new_specs = specs;
14112       else
14113 	while (specs)
14114 	  {
14115 	    tree spec;
14116             int i, len = 1;
14117             tree expanded_specs = NULL_TREE;
14118 
14119             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
14120               {
14121                 /* Expand the pack expansion type.  */
14122                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
14123                                                        args, complain,
14124                                                        in_decl);
14125 
14126 		if (expanded_specs == error_mark_node)
14127 		  return error_mark_node;
14128 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
14129 		  len = TREE_VEC_LENGTH (expanded_specs);
14130 		else
14131 		  {
14132 		    /* We're substituting into a member template, so
14133 		       we got a TYPE_PACK_EXPANSION back.  Add that
14134 		       expansion and move on.  */
14135 		    gcc_assert (TREE_CODE (expanded_specs)
14136 				== TYPE_PACK_EXPANSION);
14137 		    new_specs = add_exception_specifier (new_specs,
14138 							 expanded_specs,
14139 							 complain);
14140 		    specs = TREE_CHAIN (specs);
14141 		    continue;
14142 		  }
14143               }
14144 
14145             for (i = 0; i < len; ++i)
14146               {
14147                 if (expanded_specs)
14148                   spec = TREE_VEC_ELT (expanded_specs, i);
14149                 else
14150                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
14151                 if (spec == error_mark_node)
14152                   return spec;
14153                 new_specs = add_exception_specifier (new_specs, spec,
14154                                                      complain);
14155               }
14156 
14157             specs = TREE_CHAIN (specs);
14158 	  }
14159     }
14160   return new_specs;
14161 }
14162 
14163 /* Take the tree structure T and replace template parameters used
14164    therein with the argument vector ARGS.  IN_DECL is an associated
14165    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
14166    Issue error and warning messages under control of COMPLAIN.  Note
14167    that we must be relatively non-tolerant of extensions here, in
14168    order to preserve conformance; if we allow substitutions that
14169    should not be allowed, we may allow argument deductions that should
14170    not succeed, and therefore report ambiguous overload situations
14171    where there are none.  In theory, we could allow the substitution,
14172    but indicate that it should have failed, and allow our caller to
14173    make sure that the right thing happens, but we don't try to do this
14174    yet.
14175 
14176    This function is used for dealing with types, decls and the like;
14177    for expressions, use tsubst_expr or tsubst_copy.  */
14178 
14179 tree
14180 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
14181 {
14182   enum tree_code code;
14183   tree type, r = NULL_TREE;
14184 
14185   if (t == NULL_TREE || t == error_mark_node
14186       || t == integer_type_node
14187       || t == void_type_node
14188       || t == char_type_node
14189       || t == unknown_type_node
14190       || TREE_CODE (t) == NAMESPACE_DECL
14191       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
14192     return t;
14193 
14194   if (DECL_P (t))
14195     return tsubst_decl (t, args, complain);
14196 
14197   if (args == NULL_TREE)
14198     return t;
14199 
14200   code = TREE_CODE (t);
14201 
14202   if (code == IDENTIFIER_NODE)
14203     type = IDENTIFIER_TYPE_VALUE (t);
14204   else
14205     type = TREE_TYPE (t);
14206 
14207   gcc_assert (type != unknown_type_node);
14208 
14209   /* Reuse typedefs.  We need to do this to handle dependent attributes,
14210      such as attribute aligned.  */
14211   if (TYPE_P (t)
14212       && typedef_variant_p (t))
14213     {
14214       tree decl = TYPE_NAME (t);
14215 
14216       if (alias_template_specialization_p (t))
14217 	{
14218 	  /* DECL represents an alias template and we want to
14219 	     instantiate it.  */
14220 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14221 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14222 	  r = instantiate_alias_template (tmpl, gen_args, complain);
14223 	}
14224       else if (DECL_CLASS_SCOPE_P (decl)
14225 	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
14226 	       && uses_template_parms (DECL_CONTEXT (decl)))
14227 	{
14228 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14229 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14230 	  r = retrieve_specialization (tmpl, gen_args, 0);
14231 	}
14232       else if (DECL_FUNCTION_SCOPE_P (decl)
14233 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
14234 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
14235 	r = retrieve_local_specialization (decl);
14236       else
14237 	/* The typedef is from a non-template context.  */
14238 	return t;
14239 
14240       if (r)
14241 	{
14242 	  r = TREE_TYPE (r);
14243 	  r = cp_build_qualified_type_real
14244 	    (r, cp_type_quals (t) | cp_type_quals (r),
14245 	     complain | tf_ignore_bad_quals);
14246 	  return r;
14247 	}
14248       else
14249 	{
14250 	  /* We don't have an instantiation yet, so drop the typedef.  */
14251 	  int quals = cp_type_quals (t);
14252 	  t = DECL_ORIGINAL_TYPE (decl);
14253 	  t = cp_build_qualified_type_real (t, quals,
14254 					    complain | tf_ignore_bad_quals);
14255 	}
14256     }
14257 
14258   bool fndecl_type = (complain & tf_fndecl_type);
14259   complain &= ~tf_fndecl_type;
14260 
14261   if (type
14262       && code != TYPENAME_TYPE
14263       && code != TEMPLATE_TYPE_PARM
14264       && code != TEMPLATE_PARM_INDEX
14265       && code != IDENTIFIER_NODE
14266       && code != FUNCTION_TYPE
14267       && code != METHOD_TYPE)
14268     type = tsubst (type, args, complain, in_decl);
14269   if (type == error_mark_node)
14270     return error_mark_node;
14271 
14272   switch (code)
14273     {
14274     case RECORD_TYPE:
14275     case UNION_TYPE:
14276     case ENUMERAL_TYPE:
14277       return tsubst_aggr_type (t, args, complain, in_decl,
14278 			       /*entering_scope=*/0);
14279 
14280     case ERROR_MARK:
14281     case IDENTIFIER_NODE:
14282     case VOID_TYPE:
14283     case REAL_TYPE:
14284     case COMPLEX_TYPE:
14285     case VECTOR_TYPE:
14286     case BOOLEAN_TYPE:
14287     case NULLPTR_TYPE:
14288     case LANG_TYPE:
14289       return t;
14290 
14291     case INTEGER_TYPE:
14292       if (t == integer_type_node)
14293 	return t;
14294 
14295       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
14296           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
14297         return t;
14298 
14299       {
14300 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
14301 
14302 	max = tsubst_expr (omax, args, complain, in_decl,
14303 			   /*integral_constant_expression_p=*/false);
14304 
14305 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
14306 	   needed.  */
14307 	if (TREE_CODE (max) == NOP_EXPR
14308 	    && TREE_SIDE_EFFECTS (omax)
14309 	    && !TREE_TYPE (max))
14310 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
14311 
14312 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
14313 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
14314 	   constant expression.  */
14315 	if (processing_template_decl
14316 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
14317 	  {
14318 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
14319 	    TREE_SIDE_EFFECTS (max) = 1;
14320 	  }
14321 
14322 	return compute_array_index_type (NULL_TREE, max, complain);
14323       }
14324 
14325     case TEMPLATE_TYPE_PARM:
14326     case TEMPLATE_TEMPLATE_PARM:
14327     case BOUND_TEMPLATE_TEMPLATE_PARM:
14328     case TEMPLATE_PARM_INDEX:
14329       {
14330 	int idx;
14331 	int level;
14332 	int levels;
14333 	tree arg = NULL_TREE;
14334 
14335 	/* Early in template argument deduction substitution, we don't
14336 	   want to reduce the level of 'auto', or it will be confused
14337 	   with a normal template parm in subsequent deduction.  */
14338 	if (is_auto (t) && (complain & tf_partial))
14339 	  return t;
14340 
14341 	r = NULL_TREE;
14342 
14343 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
14344 	template_parm_level_and_index (t, &level, &idx);
14345 
14346 	levels = TMPL_ARGS_DEPTH (args);
14347 	if (level <= levels
14348 	    && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
14349 	  {
14350 	    arg = TMPL_ARG (args, level, idx);
14351 
14352 	    /* See through ARGUMENT_PACK_SELECT arguments. */
14353 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
14354 	      arg = argument_pack_select_arg (arg);
14355 	  }
14356 
14357 	if (arg == error_mark_node)
14358 	  return error_mark_node;
14359 	else if (arg != NULL_TREE)
14360 	  {
14361 	    if (ARGUMENT_PACK_P (arg))
14362 	      /* If ARG is an argument pack, we don't actually want to
14363 		 perform a substitution here, because substitutions
14364 		 for argument packs are only done
14365 		 element-by-element. We can get to this point when
14366 		 substituting the type of a non-type template
14367 		 parameter pack, when that type actually contains
14368 		 template parameter packs from an outer template, e.g.,
14369 
14370 	         template<typename... Types> struct A {
14371 		   template<Types... Values> struct B { };
14372                  };  */
14373 	      return t;
14374 
14375 	    if (code == TEMPLATE_TYPE_PARM)
14376 	      {
14377 		int quals;
14378 		gcc_assert (TYPE_P (arg));
14379 
14380 		quals = cp_type_quals (arg) | cp_type_quals (t);
14381 
14382 		return cp_build_qualified_type_real
14383 		  (arg, quals, complain | tf_ignore_bad_quals);
14384 	      }
14385 	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14386 	      {
14387 		/* We are processing a type constructed from a
14388 		   template template parameter.  */
14389 		tree argvec = tsubst (TYPE_TI_ARGS (t),
14390 				      args, complain, in_decl);
14391 		if (argvec == error_mark_node)
14392 		  return error_mark_node;
14393 
14394 		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
14395 			    || TREE_CODE (arg) == TEMPLATE_DECL
14396 			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
14397 
14398 		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
14399 		  /* Consider this code:
14400 
14401 			template <template <class> class Template>
14402 			struct Internal {
14403 			template <class Arg> using Bind = Template<Arg>;
14404 			};
14405 
14406 			template <template <class> class Template, class Arg>
14407 			using Instantiate = Template<Arg>; //#0
14408 
14409 			template <template <class> class Template,
14410                                   class Argument>
14411 			using Bind =
14412 			  Instantiate<Internal<Template>::template Bind,
14413 				      Argument>; //#1
14414 
14415 		     When #1 is parsed, the
14416 		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
14417 		     parameter `Template' in #0 matches the
14418 		     UNBOUND_CLASS_TEMPLATE representing the argument
14419 		     `Internal<Template>::template Bind'; We then want
14420 		     to assemble the type `Bind<Argument>' that can't
14421 		     be fully created right now, because
14422 		     `Internal<Template>' not being complete, the Bind
14423 		     template cannot be looked up in that context.  So
14424 		     we need to "store" `Bind<Argument>' for later
14425 		     when the context of Bind becomes complete.  Let's
14426 		     store that in a TYPENAME_TYPE.  */
14427 		  return make_typename_type (TYPE_CONTEXT (arg),
14428 					     build_nt (TEMPLATE_ID_EXPR,
14429 						       TYPE_IDENTIFIER (arg),
14430 						       argvec),
14431 					     typename_type,
14432 					     complain);
14433 
14434 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
14435 		   are resolving nested-types in the signature of a
14436 		   member function templates.  Otherwise ARG is a
14437 		   TEMPLATE_DECL and is the real template to be
14438 		   instantiated.  */
14439 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
14440 		  arg = TYPE_NAME (arg);
14441 
14442 		r = lookup_template_class (arg,
14443 					   argvec, in_decl,
14444 					   DECL_CONTEXT (arg),
14445 					    /*entering_scope=*/0,
14446 					   complain);
14447 		return cp_build_qualified_type_real
14448 		  (r, cp_type_quals (t) | cp_type_quals (r), complain);
14449 	      }
14450 	    else if (code == TEMPLATE_TEMPLATE_PARM)
14451 	      return arg;
14452 	    else
14453 	      /* TEMPLATE_PARM_INDEX.  */
14454 	      return convert_from_reference (unshare_expr (arg));
14455 	  }
14456 
14457 	if (level == 1)
14458 	  /* This can happen during the attempted tsubst'ing in
14459 	     unify.  This means that we don't yet have any information
14460 	     about the template parameter in question.  */
14461 	  return t;
14462 
14463 	/* If we get here, we must have been looking at a parm for a
14464 	   more deeply nested template.  Make a new version of this
14465 	   template parameter, but with a lower level.  */
14466 	switch (code)
14467 	  {
14468 	  case TEMPLATE_TYPE_PARM:
14469 	  case TEMPLATE_TEMPLATE_PARM:
14470 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
14471 	    if (cp_type_quals (t))
14472 	      {
14473 		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
14474 		r = cp_build_qualified_type_real
14475 		  (r, cp_type_quals (t),
14476 		   complain | (code == TEMPLATE_TYPE_PARM
14477 			       ? tf_ignore_bad_quals : 0));
14478 	      }
14479 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
14480 		     && PLACEHOLDER_TYPE_CONSTRAINTS (t)
14481 		     && (r = (TEMPLATE_PARM_DESCENDANTS
14482 			      (TEMPLATE_TYPE_PARM_INDEX (t))))
14483 		     && (r = TREE_TYPE (r))
14484 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (r))
14485 	      /* Break infinite recursion when substituting the constraints
14486 		 of a constrained placeholder.  */;
14487 	    else
14488 	      {
14489 		r = copy_type (t);
14490 		TEMPLATE_TYPE_PARM_INDEX (r)
14491 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
14492 						r, levels, args, complain);
14493 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
14494 		TYPE_MAIN_VARIANT (r) = r;
14495 		TYPE_POINTER_TO (r) = NULL_TREE;
14496 		TYPE_REFERENCE_TO (r) = NULL_TREE;
14497 
14498                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
14499 		  {
14500 		    /* Propagate constraints on placeholders.  */
14501 		    if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
14502 		      PLACEHOLDER_TYPE_CONSTRAINTS (r)
14503 			= tsubst_constraint (constr, args, complain, in_decl);
14504 		    else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
14505 		      {
14506 			pl = tsubst_copy (pl, args, complain, in_decl);
14507 			CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
14508 		      }
14509 		  }
14510 
14511 		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
14512 		  /* We have reduced the level of the template
14513 		     template parameter, but not the levels of its
14514 		     template parameters, so canonical_type_parameter
14515 		     will not be able to find the canonical template
14516 		     template parameter for this level. Thus, we
14517 		     require structural equality checking to compare
14518 		     TEMPLATE_TEMPLATE_PARMs. */
14519 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
14520 		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
14521 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
14522 		else
14523 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
14524 
14525 		if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14526 		  {
14527 		    tree tinfo = TYPE_TEMPLATE_INFO (t);
14528 		    /* We might need to substitute into the types of non-type
14529 		       template parameters.  */
14530 		    tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
14531 					complain, in_decl);
14532 		    if (tmpl == error_mark_node)
14533 		      return error_mark_node;
14534 		    tree argvec = tsubst (TI_ARGS (tinfo), args,
14535 					  complain, in_decl);
14536 		    if (argvec == error_mark_node)
14537 		      return error_mark_node;
14538 
14539 		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
14540 		      = build_template_info (tmpl, argvec);
14541 		  }
14542 	      }
14543 	    break;
14544 
14545 	  case TEMPLATE_PARM_INDEX:
14546 	    /* OK, now substitute the type of the non-type parameter.  We
14547 	       couldn't do it earlier because it might be an auto parameter,
14548 	       and we wouldn't need to if we had an argument.  */
14549 	    type = tsubst (type, args, complain, in_decl);
14550 	    if (type == error_mark_node)
14551 	      return error_mark_node;
14552 	    r = reduce_template_parm_level (t, type, levels, args, complain);
14553 	    break;
14554 
14555 	  default:
14556 	    gcc_unreachable ();
14557 	  }
14558 
14559 	return r;
14560       }
14561 
14562     case TREE_LIST:
14563       {
14564 	tree purpose, value, chain;
14565 
14566 	if (t == void_list_node)
14567 	  return t;
14568 
14569 	purpose = TREE_PURPOSE (t);
14570 	if (purpose)
14571 	  {
14572 	    purpose = tsubst (purpose, args, complain, in_decl);
14573 	    if (purpose == error_mark_node)
14574 	      return error_mark_node;
14575 	  }
14576 	value = TREE_VALUE (t);
14577 	if (value)
14578 	  {
14579 	    value = tsubst (value, args, complain, in_decl);
14580 	    if (value == error_mark_node)
14581 	      return error_mark_node;
14582 	  }
14583 	chain = TREE_CHAIN (t);
14584 	if (chain && chain != void_type_node)
14585 	  {
14586 	    chain = tsubst (chain, args, complain, in_decl);
14587 	    if (chain == error_mark_node)
14588 	      return error_mark_node;
14589 	  }
14590 	if (purpose == TREE_PURPOSE (t)
14591 	    && value == TREE_VALUE (t)
14592 	    && chain == TREE_CHAIN (t))
14593 	  return t;
14594 	return hash_tree_cons (purpose, value, chain);
14595       }
14596 
14597     case TREE_BINFO:
14598       /* We should never be tsubsting a binfo.  */
14599       gcc_unreachable ();
14600 
14601     case TREE_VEC:
14602       /* A vector of template arguments.  */
14603       gcc_assert (!type);
14604       return tsubst_template_args (t, args, complain, in_decl);
14605 
14606     case POINTER_TYPE:
14607     case REFERENCE_TYPE:
14608       {
14609 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
14610 	  return t;
14611 
14612 	/* [temp.deduct]
14613 
14614 	   Type deduction may fail for any of the following
14615 	   reasons:
14616 
14617 	   -- Attempting to create a pointer to reference type.
14618 	   -- Attempting to create a reference to a reference type or
14619 	      a reference to void.
14620 
14621 	  Core issue 106 says that creating a reference to a reference
14622 	  during instantiation is no longer a cause for failure. We
14623 	  only enforce this check in strict C++98 mode.  */
14624 	if ((TREE_CODE (type) == REFERENCE_TYPE
14625 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
14626 	    || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
14627 	  {
14628 	    static location_t last_loc;
14629 
14630 	    /* We keep track of the last time we issued this error
14631 	       message to avoid spewing a ton of messages during a
14632 	       single bad template instantiation.  */
14633 	    if (complain & tf_error
14634 		&& last_loc != input_location)
14635 	      {
14636 		if (VOID_TYPE_P (type))
14637 		  error ("forming reference to void");
14638                else if (code == POINTER_TYPE)
14639                  error ("forming pointer to reference type %qT", type);
14640                else
14641 		  error ("forming reference to reference type %qT", type);
14642 		last_loc = input_location;
14643 	      }
14644 
14645 	    return error_mark_node;
14646 	  }
14647 	else if (TREE_CODE (type) == FUNCTION_TYPE
14648 		 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
14649 		     || type_memfn_rqual (type) != REF_QUAL_NONE))
14650 	  {
14651 	    if (complain & tf_error)
14652 	      {
14653 		if (code == POINTER_TYPE)
14654 		  error ("forming pointer to qualified function type %qT",
14655 			 type);
14656 		else
14657 		  error ("forming reference to qualified function type %qT",
14658 			 type);
14659 	      }
14660 	    return error_mark_node;
14661 	  }
14662 	else if (code == POINTER_TYPE)
14663 	  {
14664 	    r = build_pointer_type (type);
14665 	    if (TREE_CODE (type) == METHOD_TYPE)
14666 	      r = build_ptrmemfunc_type (r);
14667 	  }
14668 	else if (TREE_CODE (type) == REFERENCE_TYPE)
14669 	  /* In C++0x, during template argument substitution, when there is an
14670 	     attempt to create a reference to a reference type, reference
14671 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
14672 
14673 	     "If a template-argument for a template-parameter T names a type
14674 	     that is a reference to a type A, an attempt to create the type
14675 	     'lvalue reference to cv T' creates the type 'lvalue reference to
14676 	     A,' while an attempt to create the type type rvalue reference to
14677 	     cv T' creates the type T"
14678 	  */
14679 	  r = cp_build_reference_type
14680 	      (TREE_TYPE (type),
14681 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
14682 	else
14683 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
14684 	r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
14685 
14686 	if (r != error_mark_node)
14687 	  /* Will this ever be needed for TYPE_..._TO values?  */
14688 	  layout_type (r);
14689 
14690 	return r;
14691       }
14692     case OFFSET_TYPE:
14693       {
14694 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
14695 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
14696 	  {
14697 	    /* [temp.deduct]
14698 
14699 	       Type deduction may fail for any of the following
14700 	       reasons:
14701 
14702 	       -- Attempting to create "pointer to member of T" when T
14703 		  is not a class type.  */
14704 	    if (complain & tf_error)
14705 	      error ("creating pointer to member of non-class type %qT", r);
14706 	    return error_mark_node;
14707 	  }
14708 	if (TREE_CODE (type) == REFERENCE_TYPE)
14709 	  {
14710 	    if (complain & tf_error)
14711 	      error ("creating pointer to member reference type %qT", type);
14712 	    return error_mark_node;
14713 	  }
14714 	if (VOID_TYPE_P (type))
14715 	  {
14716 	    if (complain & tf_error)
14717 	      error ("creating pointer to member of type void");
14718 	    return error_mark_node;
14719 	  }
14720 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
14721 	if (TREE_CODE (type) == FUNCTION_TYPE)
14722 	  {
14723 	    /* The type of the implicit object parameter gets its
14724 	       cv-qualifiers from the FUNCTION_TYPE. */
14725 	    tree memptr;
14726 	    tree method_type
14727 	      = build_memfn_type (type, r, type_memfn_quals (type),
14728 				  type_memfn_rqual (type));
14729 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
14730 	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
14731 						 complain);
14732 	  }
14733 	else
14734 	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
14735 					       cp_type_quals (t),
14736 					       complain);
14737       }
14738     case FUNCTION_TYPE:
14739     case METHOD_TYPE:
14740       {
14741 	tree fntype;
14742 	tree specs;
14743 	fntype = tsubst_function_type (t, args, complain, in_decl);
14744 	if (fntype == error_mark_node)
14745 	  return error_mark_node;
14746 
14747 	/* Substitute the exception specification.  */
14748 	specs = tsubst_exception_specification (t, args, complain, in_decl,
14749 						/*defer_ok*/fndecl_type);
14750 	if (specs == error_mark_node)
14751 	  return error_mark_node;
14752 	if (specs)
14753 	  fntype = build_exception_variant (fntype, specs);
14754 	return fntype;
14755       }
14756     case ARRAY_TYPE:
14757       {
14758 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
14759 	if (domain == error_mark_node)
14760 	  return error_mark_node;
14761 
14762 	/* As an optimization, we avoid regenerating the array type if
14763 	   it will obviously be the same as T.  */
14764 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
14765 	  return t;
14766 
14767 	/* These checks should match the ones in create_array_type_for_decl.
14768 
14769 	   [temp.deduct]
14770 
14771 	   The deduction may fail for any of the following reasons:
14772 
14773 	   -- Attempting to create an array with an element type that
14774 	      is void, a function type, or a reference type, or [DR337]
14775 	      an abstract class type.  */
14776 	if (VOID_TYPE_P (type)
14777 	    || TREE_CODE (type) == FUNCTION_TYPE
14778 	    || (TREE_CODE (type) == ARRAY_TYPE
14779 		&& TYPE_DOMAIN (type) == NULL_TREE)
14780 	    || TREE_CODE (type) == REFERENCE_TYPE)
14781 	  {
14782 	    if (complain & tf_error)
14783 	      error ("creating array of %qT", type);
14784 	    return error_mark_node;
14785 	  }
14786 
14787 	if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
14788 	  return error_mark_node;
14789 
14790 	r = build_cplus_array_type (type, domain);
14791 
14792 	if (TYPE_USER_ALIGN (t))
14793 	  {
14794 	    SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
14795 	    TYPE_USER_ALIGN (r) = 1;
14796 	  }
14797 
14798 	return r;
14799       }
14800 
14801     case TYPENAME_TYPE:
14802       {
14803 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
14804 				     in_decl, /*entering_scope=*/1);
14805 	if (ctx == error_mark_node)
14806 	  return error_mark_node;
14807 
14808 	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
14809 			      complain, in_decl);
14810 	if (f == error_mark_node)
14811 	  return error_mark_node;
14812 
14813 	if (!MAYBE_CLASS_TYPE_P (ctx))
14814 	  {
14815 	    if (complain & tf_error)
14816 	      error ("%qT is not a class, struct, or union type", ctx);
14817 	    return error_mark_node;
14818 	  }
14819 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
14820 	  {
14821 	    /* Normally, make_typename_type does not require that the CTX
14822 	       have complete type in order to allow things like:
14823 
14824 		 template <class T> struct S { typename S<T>::X Y; };
14825 
14826 	       But, such constructs have already been resolved by this
14827 	       point, so here CTX really should have complete type, unless
14828 	       it's a partial instantiation.  */
14829 	    ctx = complete_type (ctx);
14830 	    if (!COMPLETE_TYPE_P (ctx))
14831 	      {
14832 		if (complain & tf_error)
14833 		  cxx_incomplete_type_error (NULL_TREE, ctx);
14834 		return error_mark_node;
14835 	      }
14836 	  }
14837 
14838 	f = make_typename_type (ctx, f, typename_type,
14839 				complain | tf_keep_type_decl);
14840 	if (f == error_mark_node)
14841 	  return f;
14842 	if (TREE_CODE (f) == TYPE_DECL)
14843 	  {
14844 	    complain |= tf_ignore_bad_quals;
14845 	    f = TREE_TYPE (f);
14846 	  }
14847 
14848 	if (TREE_CODE (f) != TYPENAME_TYPE)
14849 	  {
14850 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
14851 	      {
14852 		if (complain & tf_error)
14853 		  error ("%qT resolves to %qT, which is not an enumeration type",
14854 			 t, f);
14855 		else
14856 		  return error_mark_node;
14857 	      }
14858 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
14859 	      {
14860 		if (complain & tf_error)
14861 		  error ("%qT resolves to %qT, which is is not a class type",
14862 			 t, f);
14863 		else
14864 		  return error_mark_node;
14865 	      }
14866 	  }
14867 
14868 	return cp_build_qualified_type_real
14869 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
14870       }
14871 
14872     case UNBOUND_CLASS_TEMPLATE:
14873       {
14874 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
14875 				     in_decl, /*entering_scope=*/1);
14876 	tree name = TYPE_IDENTIFIER (t);
14877 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
14878 
14879 	if (ctx == error_mark_node || name == error_mark_node)
14880 	  return error_mark_node;
14881 
14882 	if (parm_list)
14883 	  parm_list = tsubst_template_parms (parm_list, args, complain);
14884 	return make_unbound_class_template (ctx, name, parm_list, complain);
14885       }
14886 
14887     case TYPEOF_TYPE:
14888       {
14889 	tree type;
14890 
14891 	++cp_unevaluated_operand;
14892 	++c_inhibit_evaluation_warnings;
14893 
14894 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
14895 			    complain, in_decl,
14896 			    /*integral_constant_expression_p=*/false);
14897 
14898 	--cp_unevaluated_operand;
14899 	--c_inhibit_evaluation_warnings;
14900 
14901 	type = finish_typeof (type);
14902 	return cp_build_qualified_type_real (type,
14903 					     cp_type_quals (t)
14904 					     | cp_type_quals (type),
14905 					     complain);
14906       }
14907 
14908     case DECLTYPE_TYPE:
14909       {
14910 	tree type;
14911 
14912 	++cp_unevaluated_operand;
14913 	++c_inhibit_evaluation_warnings;
14914 
14915 	type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
14916 				      complain|tf_decltype, in_decl,
14917 				      /*function_p*/false,
14918 				      /*integral_constant_expression*/false);
14919 
14920 	if (DECLTYPE_FOR_INIT_CAPTURE (t))
14921 	  {
14922 	    if (type == NULL_TREE)
14923 	      {
14924 		if (complain & tf_error)
14925 		  error ("empty initializer in lambda init-capture");
14926 		type = error_mark_node;
14927 	      }
14928 	    else if (TREE_CODE (type) == TREE_LIST)
14929 	      type = build_x_compound_expr_from_list (type, ELK_INIT, complain);
14930 	  }
14931 
14932 	--cp_unevaluated_operand;
14933 	--c_inhibit_evaluation_warnings;
14934 
14935 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
14936 	  type = lambda_capture_field_type (type,
14937 					    DECLTYPE_FOR_INIT_CAPTURE (t),
14938 					    DECLTYPE_FOR_REF_CAPTURE (t));
14939 	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
14940 	  type = lambda_proxy_type (type);
14941 	else
14942 	  {
14943 	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
14944 	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
14945 		&& EXPR_P (type))
14946 	      /* In a template ~id could be either a complement expression
14947 		 or an unqualified-id naming a destructor; if instantiating
14948 		 it produces an expression, it's not an id-expression or
14949 		 member access.  */
14950 	      id = false;
14951 	    type = finish_decltype_type (type, id, complain);
14952 	  }
14953 	return cp_build_qualified_type_real (type,
14954 					     cp_type_quals (t)
14955 					     | cp_type_quals (type),
14956 					     complain | tf_ignore_bad_quals);
14957       }
14958 
14959     case UNDERLYING_TYPE:
14960       {
14961 	tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
14962 			    complain, in_decl);
14963 	return finish_underlying_type (type);
14964       }
14965 
14966     case TYPE_ARGUMENT_PACK:
14967     case NONTYPE_ARGUMENT_PACK:
14968       {
14969         tree r;
14970 
14971 	if (code == NONTYPE_ARGUMENT_PACK)
14972 	  r = make_node (code);
14973 	else
14974 	  r = cxx_make_type (code);
14975 
14976 	tree pack_args = ARGUMENT_PACK_ARGS (t);
14977 	pack_args = tsubst_template_args (pack_args, args, complain, in_decl);
14978 	SET_ARGUMENT_PACK_ARGS (r, pack_args);
14979 
14980 	return r;
14981       }
14982 
14983     case VOID_CST:
14984     case INTEGER_CST:
14985     case REAL_CST:
14986     case STRING_CST:
14987     case PLUS_EXPR:
14988     case MINUS_EXPR:
14989     case NEGATE_EXPR:
14990     case NOP_EXPR:
14991     case INDIRECT_REF:
14992     case ADDR_EXPR:
14993     case CALL_EXPR:
14994     case ARRAY_REF:
14995     case SCOPE_REF:
14996       /* We should use one of the expression tsubsts for these codes.  */
14997       gcc_unreachable ();
14998 
14999     default:
15000       sorry ("use of %qs in template", get_tree_code_name (code));
15001       return error_mark_node;
15002     }
15003 }
15004 
15005 /* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
15006    expression on the left-hand side of the "." or "->" operator.  We
15007    only do the lookup if we had a dependent BASELINK.  Otherwise we
15008    adjust it onto the instantiated heirarchy.  */
15009 
15010 static tree
15011 tsubst_baselink (tree baselink, tree object_type,
15012 		 tree args, tsubst_flags_t complain, tree in_decl)
15013 {
15014   bool qualified_p = BASELINK_QUALIFIED_P (baselink);
15015   tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
15016   qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
15017 
15018   tree optype = BASELINK_OPTYPE (baselink);
15019   optype = tsubst (optype, args, complain, in_decl);
15020 
15021   tree template_args = NULL_TREE;
15022   bool template_id_p = false;
15023   tree fns = BASELINK_FUNCTIONS (baselink);
15024   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
15025     {
15026       template_id_p = true;
15027       template_args = TREE_OPERAND (fns, 1);
15028       fns = TREE_OPERAND (fns, 0);
15029       if (template_args)
15030 	template_args = tsubst_template_args (template_args, args,
15031 					      complain, in_decl);
15032     }
15033 
15034   tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
15035   binfo_type = tsubst (binfo_type, args, complain, in_decl);
15036   bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
15037 
15038   if (dependent_p)
15039     {
15040       tree name = OVL_NAME (fns);
15041       if (IDENTIFIER_CONV_OP_P (name))
15042 	name = make_conv_op_name (optype);
15043 
15044       if (name == complete_dtor_identifier)
15045 	/* Treat as-if non-dependent below.  */
15046 	dependent_p = false;
15047 
15048       baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
15049       if (!baselink)
15050 	{
15051 	  if ((complain & tf_error)
15052 	      && constructor_name_p (name, qualifying_scope))
15053 	    error ("cannot call constructor %<%T::%D%> directly",
15054 		   qualifying_scope, name);
15055 	  return error_mark_node;
15056 	}
15057 
15058       if (BASELINK_P (baselink))
15059 	fns = BASELINK_FUNCTIONS (baselink);
15060     }
15061   else
15062     /* We're going to overwrite pieces below, make a duplicate.  */
15063     baselink = copy_node (baselink);
15064 
15065   /* If lookup found a single function, mark it as used at this point.
15066      (If lookup found multiple functions the one selected later by
15067      overload resolution will be marked as used at that point.)  */
15068   if (!template_id_p && !really_overloaded_fn (fns))
15069     {
15070       tree fn = OVL_FIRST (fns);
15071       bool ok = mark_used (fn, complain);
15072       if (!ok && !(complain & tf_error))
15073 	return error_mark_node;
15074       if (ok && BASELINK_P (baselink))
15075 	/* We might have instantiated an auto function.  */
15076 	TREE_TYPE (baselink) = TREE_TYPE (fn);
15077     }
15078 
15079   if (BASELINK_P (baselink))
15080     {
15081       /* Add back the template arguments, if present.  */
15082       if (template_id_p)
15083 	BASELINK_FUNCTIONS (baselink)
15084 	  = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
15085 
15086       /* Update the conversion operator type.  */
15087       BASELINK_OPTYPE (baselink) = optype;
15088     }
15089 
15090   if (!object_type)
15091     object_type = current_class_type;
15092 
15093   if (qualified_p || !dependent_p)
15094     {
15095       baselink = adjust_result_of_qualified_name_lookup (baselink,
15096 							 qualifying_scope,
15097 							 object_type);
15098       if (!qualified_p)
15099 	/* We need to call adjust_result_of_qualified_name_lookup in case the
15100 	   destructor names a base class, but we unset BASELINK_QUALIFIED_P
15101 	   so that we still get virtual function binding.  */
15102 	BASELINK_QUALIFIED_P (baselink) = false;
15103     }
15104 
15105   return baselink;
15106 }
15107 
15108 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
15109    true if the qualified-id will be a postfix-expression in-and-of
15110    itself; false if more of the postfix-expression follows the
15111    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
15112    of "&".  */
15113 
15114 static tree
15115 tsubst_qualified_id (tree qualified_id, tree args,
15116 		     tsubst_flags_t complain, tree in_decl,
15117 		     bool done, bool address_p)
15118 {
15119   tree expr;
15120   tree scope;
15121   tree name;
15122   bool is_template;
15123   tree template_args;
15124   location_t loc = UNKNOWN_LOCATION;
15125 
15126   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
15127 
15128   /* Figure out what name to look up.  */
15129   name = TREE_OPERAND (qualified_id, 1);
15130   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
15131     {
15132       is_template = true;
15133       loc = EXPR_LOCATION (name);
15134       template_args = TREE_OPERAND (name, 1);
15135       if (template_args)
15136 	template_args = tsubst_template_args (template_args, args,
15137 					      complain, in_decl);
15138       if (template_args == error_mark_node)
15139 	return error_mark_node;
15140       name = TREE_OPERAND (name, 0);
15141     }
15142   else
15143     {
15144       is_template = false;
15145       template_args = NULL_TREE;
15146     }
15147 
15148   /* Substitute into the qualifying scope.  When there are no ARGS, we
15149      are just trying to simplify a non-dependent expression.  In that
15150      case the qualifying scope may be dependent, and, in any case,
15151      substituting will not help.  */
15152   scope = TREE_OPERAND (qualified_id, 0);
15153   if (args)
15154     {
15155       scope = tsubst (scope, args, complain, in_decl);
15156       expr = tsubst_copy (name, args, complain, in_decl);
15157     }
15158   else
15159     expr = name;
15160 
15161   if (dependent_scope_p (scope))
15162     {
15163       if (is_template)
15164 	expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
15165       tree r = build_qualified_name (NULL_TREE, scope, expr,
15166 				     QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
15167       REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
15168       return r;
15169     }
15170 
15171   if (!BASELINK_P (name) && !DECL_P (expr))
15172     {
15173       if (TREE_CODE (expr) == BIT_NOT_EXPR)
15174 	{
15175 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
15176 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
15177 	    {
15178 	      error ("qualifying type %qT does not match destructor name ~%qT",
15179 		     scope, TREE_OPERAND (expr, 0));
15180 	      expr = error_mark_node;
15181 	    }
15182 	  else
15183 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
15184 					  /*is_type_p=*/0, false);
15185 	}
15186       else
15187 	expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
15188       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
15189 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
15190 	{
15191 	  if (complain & tf_error)
15192 	    {
15193 	      error ("dependent-name %qE is parsed as a non-type, but "
15194 		     "instantiation yields a type", qualified_id);
15195 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
15196 	    }
15197 	  return error_mark_node;
15198 	}
15199     }
15200 
15201   if (DECL_P (expr))
15202     {
15203       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
15204 					   scope);
15205       /* Remember that there was a reference to this entity.  */
15206       if (!mark_used (expr, complain) && !(complain & tf_error))
15207 	return error_mark_node;
15208     }
15209 
15210   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
15211     {
15212       if (complain & tf_error)
15213 	qualified_name_lookup_error (scope,
15214 				     TREE_OPERAND (qualified_id, 1),
15215 				     expr, input_location);
15216       return error_mark_node;
15217     }
15218 
15219   if (is_template)
15220     {
15221       /* We may be repeating a check already done during parsing, but
15222 	 if it was well-formed and passed then, it will pass again
15223 	 now, and if it didn't, we wouldn't have got here.  The case
15224 	 we want to catch is when we couldn't tell then, and can now,
15225 	 namely when templ prior to substitution was an
15226 	 identifier.  */
15227       if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
15228 	return error_mark_node;
15229 
15230       if (variable_template_p (expr))
15231 	expr = lookup_and_finish_template_variable (expr, template_args,
15232 						    complain);
15233       else
15234 	expr = lookup_template_function (expr, template_args);
15235     }
15236 
15237   if (expr == error_mark_node && complain & tf_error)
15238     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
15239 				 expr, input_location);
15240   else if (TYPE_P (scope))
15241     {
15242       expr = (adjust_result_of_qualified_name_lookup
15243 	      (expr, scope, current_nonlambda_class_type ()));
15244       expr = (finish_qualified_id_expr
15245 	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
15246 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
15247 	       /*template_arg_p=*/false, complain));
15248     }
15249 
15250   /* Expressions do not generally have reference type.  */
15251   if (TREE_CODE (expr) != SCOPE_REF
15252       /* However, if we're about to form a pointer-to-member, we just
15253 	 want the referenced member referenced.  */
15254       && TREE_CODE (expr) != OFFSET_REF)
15255     expr = convert_from_reference (expr);
15256 
15257   if (REF_PARENTHESIZED_P (qualified_id))
15258     expr = force_paren_expr (expr);
15259 
15260   return expr;
15261 }
15262 
15263 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
15264    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
15265    for tsubst.  */
15266 
15267 static tree
15268 tsubst_init (tree init, tree decl, tree args,
15269 	     tsubst_flags_t complain, tree in_decl)
15270 {
15271   if (!init)
15272     return NULL_TREE;
15273 
15274   init = tsubst_expr (init, args, complain, in_decl, false);
15275 
15276   if (!init && TREE_TYPE (decl) != error_mark_node)
15277     {
15278       /* If we had an initializer but it
15279 	 instantiated to nothing,
15280 	 value-initialize the object.  This will
15281 	 only occur when the initializer was a
15282 	 pack expansion where the parameter packs
15283 	 used in that expansion were of length
15284 	 zero.  */
15285       init = build_value_init (TREE_TYPE (decl),
15286 			       complain);
15287       if (TREE_CODE (init) == AGGR_INIT_EXPR)
15288 	init = get_target_expr_sfinae (init, complain);
15289       if (TREE_CODE (init) == TARGET_EXPR)
15290 	TARGET_EXPR_DIRECT_INIT_P (init) = true;
15291     }
15292 
15293   return init;
15294 }
15295 
15296 /* Like tsubst, but deals with expressions.  This function just replaces
15297    template parms; to finish processing the resultant expression, use
15298    tsubst_copy_and_build or tsubst_expr.  */
15299 
15300 static tree
15301 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15302 {
15303   enum tree_code code;
15304   tree r;
15305 
15306   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
15307     return t;
15308 
15309   code = TREE_CODE (t);
15310 
15311   switch (code)
15312     {
15313     case PARM_DECL:
15314       r = retrieve_local_specialization (t);
15315 
15316       if (r == NULL_TREE)
15317 	{
15318 	  /* We get here for a use of 'this' in an NSDMI.  */
15319 	  if (DECL_NAME (t) == this_identifier && current_class_ptr)
15320 	    return current_class_ptr;
15321 
15322 	  /* This can happen for a parameter name used later in a function
15323 	     declaration (such as in a late-specified return type).  Just
15324 	     make a dummy decl, since it's only used for its type.  */
15325 	  gcc_assert (cp_unevaluated_operand != 0);
15326 	  r = tsubst_decl (t, args, complain);
15327 	  /* Give it the template pattern as its context; its true context
15328 	     hasn't been instantiated yet and this is good enough for
15329 	     mangling.  */
15330 	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
15331 	}
15332 
15333       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15334 	r = argument_pack_select_arg (r);
15335       if (!mark_used (r, complain) && !(complain & tf_error))
15336 	return error_mark_node;
15337       return r;
15338 
15339     case CONST_DECL:
15340       {
15341 	tree enum_type;
15342 	tree v;
15343 
15344 	if (DECL_TEMPLATE_PARM_P (t))
15345 	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
15346 	/* There is no need to substitute into namespace-scope
15347 	   enumerators.  */
15348 	if (DECL_NAMESPACE_SCOPE_P (t))
15349 	  return t;
15350 	/* If ARGS is NULL, then T is known to be non-dependent.  */
15351 	if (args == NULL_TREE)
15352 	  return scalar_constant_value (t);
15353 
15354 	/* Unfortunately, we cannot just call lookup_name here.
15355 	   Consider:
15356 
15357 	     template <int I> int f() {
15358 	     enum E { a = I };
15359 	     struct S { void g() { E e = a; } };
15360 	     };
15361 
15362 	   When we instantiate f<7>::S::g(), say, lookup_name is not
15363 	   clever enough to find f<7>::a.  */
15364 	enum_type
15365 	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15366 			      /*entering_scope=*/0);
15367 
15368 	for (v = TYPE_VALUES (enum_type);
15369 	     v != NULL_TREE;
15370 	     v = TREE_CHAIN (v))
15371 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
15372 	    return TREE_VALUE (v);
15373 
15374 	  /* We didn't find the name.  That should never happen; if
15375 	     name-lookup found it during preliminary parsing, we
15376 	     should find it again here during instantiation.  */
15377 	gcc_unreachable ();
15378       }
15379       return t;
15380 
15381     case FIELD_DECL:
15382       if (DECL_CONTEXT (t))
15383 	{
15384 	  tree ctx;
15385 
15386 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15387 				  /*entering_scope=*/1);
15388 	  if (ctx != DECL_CONTEXT (t))
15389 	    {
15390 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
15391 	      if (!r)
15392 		{
15393 		  if (complain & tf_error)
15394 		    error ("using invalid field %qD", t);
15395 		  return error_mark_node;
15396 		}
15397 	      return r;
15398 	    }
15399 	}
15400 
15401       return t;
15402 
15403     case VAR_DECL:
15404     case FUNCTION_DECL:
15405       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
15406 	r = tsubst (t, args, complain, in_decl);
15407       else if (local_variable_p (t)
15408 	       && uses_template_parms (DECL_CONTEXT (t)))
15409 	{
15410 	  r = retrieve_local_specialization (t);
15411 	  if (r == NULL_TREE)
15412 	    {
15413 	      /* First try name lookup to find the instantiation.  */
15414 	      r = lookup_name (DECL_NAME (t));
15415 	      if (r && !is_capture_proxy (r))
15416 		{
15417 		  /* Make sure that the one we found is the one we want.  */
15418 		  tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
15419 		  if (ctx != DECL_CONTEXT (r))
15420 		    r = NULL_TREE;
15421 		}
15422 
15423 	      if (r)
15424 		/* OK */;
15425 	      else
15426 		{
15427 		  /* This can happen for a variable used in a
15428 		     late-specified return type of a local lambda, or for a
15429 		     local static or constant.  Building a new VAR_DECL
15430 		     should be OK in all those cases.  */
15431 		  r = tsubst_decl (t, args, complain);
15432 		  if (local_specializations)
15433 		    /* Avoid infinite recursion (79640).  */
15434 		    register_local_specialization (r, t);
15435 		  if (decl_maybe_constant_var_p (r))
15436 		    {
15437 		      /* We can't call cp_finish_decl, so handle the
15438 			 initializer by hand.  */
15439 		      tree init = tsubst_init (DECL_INITIAL (t), r, args,
15440 					       complain, in_decl);
15441 		      if (!processing_template_decl)
15442 			init = maybe_constant_init (init);
15443 		      if (processing_template_decl
15444 			  ? potential_constant_expression (init)
15445 			  : reduced_constant_expression_p (init))
15446 			DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
15447 			  = TREE_CONSTANT (r) = true;
15448 		      DECL_INITIAL (r) = init;
15449 		      if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
15450 			TREE_TYPE (r)
15451 			  = do_auto_deduction (TREE_TYPE (r), init, auto_node,
15452 					       complain, adc_variable_type);
15453 		    }
15454 		  gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
15455 			      || decl_constant_var_p (r)
15456 			      || errorcount || sorrycount);
15457 		  if (!processing_template_decl
15458 		      && !TREE_STATIC (r))
15459 		    r = process_outer_var_ref (r, complain);
15460 		}
15461 	      /* Remember this for subsequent uses.  */
15462 	      if (local_specializations)
15463 		register_local_specialization (r, t);
15464 	    }
15465 	  if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15466 	    r = argument_pack_select_arg (r);
15467 	}
15468       else
15469 	r = t;
15470       if (!mark_used (r, complain))
15471 	return error_mark_node;
15472       return r;
15473 
15474     case NAMESPACE_DECL:
15475       return t;
15476 
15477     case OVERLOAD:
15478       /* An OVERLOAD will always be a non-dependent overload set; an
15479 	 overload set from function scope will just be represented with an
15480 	 IDENTIFIER_NODE, and from class scope with a BASELINK.  */
15481       gcc_assert (!uses_template_parms (t));
15482       /* We must have marked any lookups as persistent.  */
15483       gcc_assert (!OVL_LOOKUP_P (t) || OVL_USED_P (t));
15484       return t;
15485 
15486     case BASELINK:
15487       return tsubst_baselink (t, current_nonlambda_class_type (),
15488 			      args, complain, in_decl);
15489 
15490     case TEMPLATE_DECL:
15491       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
15492 	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
15493 		       args, complain, in_decl);
15494       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
15495 	return tsubst (t, args, complain, in_decl);
15496       else if (DECL_CLASS_SCOPE_P (t)
15497 	       && uses_template_parms (DECL_CONTEXT (t)))
15498 	{
15499 	  /* Template template argument like the following example need
15500 	     special treatment:
15501 
15502 	       template <template <class> class TT> struct C {};
15503 	       template <class T> struct D {
15504 		 template <class U> struct E {};
15505 		 C<E> c;				// #1
15506 	       };
15507 	       D<int> d;				// #2
15508 
15509 	     We are processing the template argument `E' in #1 for
15510 	     the template instantiation #2.  Originally, `E' is a
15511 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
15512 	     have to substitute this with one having context `D<int>'.  */
15513 
15514 	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
15515 	  if (dependent_scope_p (context))
15516 	    {
15517 	      /* When rewriting a constructor into a deduction guide, a
15518 		 non-dependent name can become dependent, so memtmpl<args>
15519 		 becomes context::template memtmpl<args>.  */
15520 	      tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15521 	      return build_qualified_name (type, context, DECL_NAME (t),
15522 					   /*template*/true);
15523 	    }
15524 	  return lookup_field (context, DECL_NAME(t), 0, false);
15525 	}
15526       else
15527 	/* Ordinary template template argument.  */
15528 	return t;
15529 
15530     case NON_LVALUE_EXPR:
15531     case VIEW_CONVERT_EXPR:
15532 	{
15533 	  /* Handle location wrappers by substituting the wrapped node
15534 	     first, *then* reusing the resulting type.  Doing the type
15535 	     first ensures that we handle template parameters and
15536 	     parameter pack expansions.  */
15537 	  gcc_assert (location_wrapper_p (t));
15538 	  tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15539 	  return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
15540 	}
15541 
15542     case CAST_EXPR:
15543     case REINTERPRET_CAST_EXPR:
15544     case CONST_CAST_EXPR:
15545     case STATIC_CAST_EXPR:
15546     case DYNAMIC_CAST_EXPR:
15547     case IMPLICIT_CONV_EXPR:
15548     case CONVERT_EXPR:
15549     case NOP_EXPR:
15550       {
15551 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15552 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15553 	return build1 (code, type, op0);
15554       }
15555 
15556     case SIZEOF_EXPR:
15557       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
15558 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
15559         {
15560           tree expanded, op = TREE_OPERAND (t, 0);
15561 	  int len = 0;
15562 
15563 	  if (SIZEOF_EXPR_TYPE_P (t))
15564 	    op = TREE_TYPE (op);
15565 
15566 	  ++cp_unevaluated_operand;
15567 	  ++c_inhibit_evaluation_warnings;
15568 	  /* We only want to compute the number of arguments.  */
15569 	  if (PACK_EXPANSION_P (op))
15570 	    expanded = tsubst_pack_expansion (op, args, complain, in_decl);
15571 	  else
15572 	    expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
15573 					     args, complain, in_decl);
15574 	  --cp_unevaluated_operand;
15575 	  --c_inhibit_evaluation_warnings;
15576 
15577 	  if (TREE_CODE (expanded) == TREE_VEC)
15578 	    {
15579 	      len = TREE_VEC_LENGTH (expanded);
15580 	      /* Set TREE_USED for the benefit of -Wunused.  */
15581 	      for (int i = 0; i < len; i++)
15582 		if (DECL_P (TREE_VEC_ELT (expanded, i)))
15583 		  TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
15584 	    }
15585 
15586 	  if (expanded == error_mark_node)
15587 	    return error_mark_node;
15588 	  else if (PACK_EXPANSION_P (expanded)
15589 		   || (TREE_CODE (expanded) == TREE_VEC
15590 		       && pack_expansion_args_count (expanded)))
15591 
15592 	    {
15593 	      if (PACK_EXPANSION_P (expanded))
15594 		/* OK.  */;
15595 	      else if (TREE_VEC_LENGTH (expanded) == 1)
15596 		expanded = TREE_VEC_ELT (expanded, 0);
15597 	      else
15598 		expanded = make_argument_pack (expanded);
15599 
15600 	      if (TYPE_P (expanded))
15601 		return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR,
15602 						   false,
15603 						   complain & tf_error);
15604 	      else
15605 		return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
15606                                                    complain & tf_error);
15607 	    }
15608 	  else
15609 	    return build_int_cst (size_type_node, len);
15610         }
15611       if (SIZEOF_EXPR_TYPE_P (t))
15612 	{
15613 	  r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
15614 		      args, complain, in_decl);
15615 	  r = build1 (NOP_EXPR, r, error_mark_node);
15616 	  r = build1 (SIZEOF_EXPR,
15617 		      tsubst (TREE_TYPE (t), args, complain, in_decl), r);
15618 	  SIZEOF_EXPR_TYPE_P (r) = 1;
15619 	  return r;
15620 	}
15621       /* Fall through */
15622 
15623     case INDIRECT_REF:
15624     case NEGATE_EXPR:
15625     case TRUTH_NOT_EXPR:
15626     case BIT_NOT_EXPR:
15627     case ADDR_EXPR:
15628     case UNARY_PLUS_EXPR:      /* Unary + */
15629     case ALIGNOF_EXPR:
15630     case AT_ENCODE_EXPR:
15631     case ARROW_EXPR:
15632     case THROW_EXPR:
15633     case TYPEID_EXPR:
15634     case REALPART_EXPR:
15635     case IMAGPART_EXPR:
15636     case PAREN_EXPR:
15637       {
15638 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15639 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15640 	r = build1 (code, type, op0);
15641 	if (code == ALIGNOF_EXPR)
15642 	  ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
15643 	return r;
15644       }
15645 
15646     case COMPONENT_REF:
15647       {
15648 	tree object;
15649 	tree name;
15650 
15651 	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15652 	name = TREE_OPERAND (t, 1);
15653 	if (TREE_CODE (name) == BIT_NOT_EXPR)
15654 	  {
15655 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
15656 				complain, in_decl);
15657 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15658 	  }
15659 	else if (TREE_CODE (name) == SCOPE_REF
15660 		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
15661 	  {
15662 	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
15663 				     complain, in_decl);
15664 	    name = TREE_OPERAND (name, 1);
15665 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
15666 				complain, in_decl);
15667 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15668 	    name = build_qualified_name (/*type=*/NULL_TREE,
15669 					 base, name,
15670 					 /*template_p=*/false);
15671 	  }
15672 	else if (BASELINK_P (name))
15673 	  name = tsubst_baselink (name,
15674 				  non_reference (TREE_TYPE (object)),
15675 				  args, complain,
15676 				  in_decl);
15677 	else
15678 	  name = tsubst_copy (name, args, complain, in_decl);
15679 	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
15680       }
15681 
15682     case PLUS_EXPR:
15683     case MINUS_EXPR:
15684     case MULT_EXPR:
15685     case TRUNC_DIV_EXPR:
15686     case CEIL_DIV_EXPR:
15687     case FLOOR_DIV_EXPR:
15688     case ROUND_DIV_EXPR:
15689     case EXACT_DIV_EXPR:
15690     case BIT_AND_EXPR:
15691     case BIT_IOR_EXPR:
15692     case BIT_XOR_EXPR:
15693     case TRUNC_MOD_EXPR:
15694     case FLOOR_MOD_EXPR:
15695     case TRUTH_ANDIF_EXPR:
15696     case TRUTH_ORIF_EXPR:
15697     case TRUTH_AND_EXPR:
15698     case TRUTH_OR_EXPR:
15699     case RSHIFT_EXPR:
15700     case LSHIFT_EXPR:
15701     case RROTATE_EXPR:
15702     case LROTATE_EXPR:
15703     case EQ_EXPR:
15704     case NE_EXPR:
15705     case MAX_EXPR:
15706     case MIN_EXPR:
15707     case LE_EXPR:
15708     case GE_EXPR:
15709     case LT_EXPR:
15710     case GT_EXPR:
15711     case COMPOUND_EXPR:
15712     case DOTSTAR_EXPR:
15713     case MEMBER_REF:
15714     case PREDECREMENT_EXPR:
15715     case PREINCREMENT_EXPR:
15716     case POSTDECREMENT_EXPR:
15717     case POSTINCREMENT_EXPR:
15718       {
15719 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15720 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15721 	return build_nt (code, op0, op1);
15722       }
15723 
15724     case SCOPE_REF:
15725       {
15726 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15727 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15728 	return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
15729 				     QUALIFIED_NAME_IS_TEMPLATE (t));
15730       }
15731 
15732     case ARRAY_REF:
15733       {
15734 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15735 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15736 	return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
15737       }
15738 
15739     case CALL_EXPR:
15740       {
15741 	int n = VL_EXP_OPERAND_LENGTH (t);
15742 	tree result = build_vl_exp (CALL_EXPR, n);
15743 	int i;
15744 	for (i = 0; i < n; i++)
15745 	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
15746 					     complain, in_decl);
15747 	return result;
15748       }
15749 
15750     case COND_EXPR:
15751     case MODOP_EXPR:
15752     case PSEUDO_DTOR_EXPR:
15753     case VEC_PERM_EXPR:
15754       {
15755 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15756 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15757 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
15758 	r = build_nt (code, op0, op1, op2);
15759 	TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
15760 	return r;
15761       }
15762 
15763     case NEW_EXPR:
15764       {
15765 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15766 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15767 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
15768 	r = build_nt (code, op0, op1, op2);
15769 	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
15770 	return r;
15771       }
15772 
15773     case DELETE_EXPR:
15774       {
15775 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15776 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15777 	r = build_nt (code, op0, op1);
15778 	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
15779 	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
15780 	return r;
15781       }
15782 
15783     case TEMPLATE_ID_EXPR:
15784       {
15785 	/* Substituted template arguments */
15786 	tree fn = TREE_OPERAND (t, 0);
15787 	tree targs = TREE_OPERAND (t, 1);
15788 
15789 	fn = tsubst_copy (fn, args, complain, in_decl);
15790 	if (targs)
15791 	  targs = tsubst_template_args (targs, args, complain, in_decl);
15792 
15793 	return lookup_template_function (fn, targs);
15794       }
15795 
15796     case TREE_LIST:
15797       {
15798 	tree purpose, value, chain;
15799 
15800 	if (t == void_list_node)
15801 	  return t;
15802 
15803 	purpose = TREE_PURPOSE (t);
15804 	if (purpose)
15805 	  purpose = tsubst_copy (purpose, args, complain, in_decl);
15806 	value = TREE_VALUE (t);
15807 	if (value)
15808 	  value = tsubst_copy (value, args, complain, in_decl);
15809 	chain = TREE_CHAIN (t);
15810 	if (chain && chain != void_type_node)
15811 	  chain = tsubst_copy (chain, args, complain, in_decl);
15812 	if (purpose == TREE_PURPOSE (t)
15813 	    && value == TREE_VALUE (t)
15814 	    && chain == TREE_CHAIN (t))
15815 	  return t;
15816 	return tree_cons (purpose, value, chain);
15817       }
15818 
15819     case RECORD_TYPE:
15820     case UNION_TYPE:
15821     case ENUMERAL_TYPE:
15822     case INTEGER_TYPE:
15823     case TEMPLATE_TYPE_PARM:
15824     case TEMPLATE_TEMPLATE_PARM:
15825     case BOUND_TEMPLATE_TEMPLATE_PARM:
15826     case TEMPLATE_PARM_INDEX:
15827     case POINTER_TYPE:
15828     case REFERENCE_TYPE:
15829     case OFFSET_TYPE:
15830     case FUNCTION_TYPE:
15831     case METHOD_TYPE:
15832     case ARRAY_TYPE:
15833     case TYPENAME_TYPE:
15834     case UNBOUND_CLASS_TEMPLATE:
15835     case TYPEOF_TYPE:
15836     case DECLTYPE_TYPE:
15837     case TYPE_DECL:
15838       return tsubst (t, args, complain, in_decl);
15839 
15840     case USING_DECL:
15841       t = DECL_NAME (t);
15842       /* Fall through.  */
15843     case IDENTIFIER_NODE:
15844       if (IDENTIFIER_CONV_OP_P (t))
15845 	{
15846 	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15847 	  return make_conv_op_name (new_type);
15848 	}
15849       else
15850 	return t;
15851 
15852     case CONSTRUCTOR:
15853       /* This is handled by tsubst_copy_and_build.  */
15854       gcc_unreachable ();
15855 
15856     case VA_ARG_EXPR:
15857       {
15858 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15859 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15860 	return build_x_va_arg (EXPR_LOCATION (t), op0, type);
15861       }
15862 
15863     case CLEANUP_POINT_EXPR:
15864       /* We shouldn't have built any of these during initial template
15865 	 generation.  Instead, they should be built during instantiation
15866 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
15867       gcc_unreachable ();
15868 
15869     case OFFSET_REF:
15870       {
15871 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15872 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15873 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15874 	r = build2 (code, type, op0, op1);
15875 	PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
15876 	if (!mark_used (TREE_OPERAND (r, 1), complain)
15877 	    && !(complain & tf_error))
15878 	  return error_mark_node;
15879 	return r;
15880       }
15881 
15882     case EXPR_PACK_EXPANSION:
15883       error ("invalid use of pack expansion expression");
15884       return error_mark_node;
15885 
15886     case NONTYPE_ARGUMENT_PACK:
15887       error ("use %<...%> to expand argument pack");
15888       return error_mark_node;
15889 
15890     case VOID_CST:
15891       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
15892       return t;
15893 
15894     case INTEGER_CST:
15895     case REAL_CST:
15896     case STRING_CST:
15897     case COMPLEX_CST:
15898       {
15899 	/* Instantiate any typedefs in the type.  */
15900 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15901 	r = fold_convert (type, t);
15902 	gcc_assert (TREE_CODE (r) == code);
15903 	return r;
15904       }
15905 
15906     case PTRMEM_CST:
15907       /* These can sometimes show up in a partial instantiation, but never
15908 	 involve template parms.  */
15909       gcc_assert (!uses_template_parms (t));
15910       return t;
15911 
15912     case UNARY_LEFT_FOLD_EXPR:
15913       return tsubst_unary_left_fold (t, args, complain, in_decl);
15914     case UNARY_RIGHT_FOLD_EXPR:
15915       return tsubst_unary_right_fold (t, args, complain, in_decl);
15916     case BINARY_LEFT_FOLD_EXPR:
15917       return tsubst_binary_left_fold (t, args, complain, in_decl);
15918     case BINARY_RIGHT_FOLD_EXPR:
15919       return tsubst_binary_right_fold (t, args, complain, in_decl);
15920     case PREDICT_EXPR:
15921       return t;
15922 
15923     case DEBUG_BEGIN_STMT:
15924       /* ??? There's no point in copying it for now, but maybe some
15925 	 day it will contain more information, such as a pointer back
15926 	 to the containing function, inlined copy or so.  */
15927       return t;
15928 
15929     default:
15930       /* We shouldn't get here, but keep going if !flag_checking.  */
15931       if (flag_checking)
15932 	gcc_unreachable ();
15933       return t;
15934     }
15935 }
15936 
15937 /* Helper function for tsubst_omp_clauses, used for instantiation of
15938    OMP_CLAUSE_DECL of clauses.  */
15939 
15940 static tree
15941 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
15942 			tree in_decl)
15943 {
15944   if (decl == NULL_TREE)
15945     return NULL_TREE;
15946 
15947   /* Handle an OpenMP array section represented as a TREE_LIST (or
15948      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
15949      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
15950      TREE_LIST.  We can handle it exactly the same as an array section
15951      (purpose, value, and a chain), even though the nomenclature
15952      (low_bound, length, etc) is different.  */
15953   if (TREE_CODE (decl) == TREE_LIST)
15954     {
15955       tree low_bound
15956 	= tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
15957 		       /*integral_constant_expression_p=*/false);
15958       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
15959 				 /*integral_constant_expression_p=*/false);
15960       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
15961 					   in_decl);
15962       if (TREE_PURPOSE (decl) == low_bound
15963 	  && TREE_VALUE (decl) == length
15964 	  && TREE_CHAIN (decl) == chain)
15965 	return decl;
15966       tree ret = tree_cons (low_bound, length, chain);
15967       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
15968 	= OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
15969       return ret;
15970     }
15971   tree ret = tsubst_expr (decl, args, complain, in_decl,
15972 			  /*integral_constant_expression_p=*/false);
15973   /* Undo convert_from_reference tsubst_expr could have called.  */
15974   if (decl
15975       && REFERENCE_REF_P (ret)
15976       && !REFERENCE_REF_P (decl))
15977     ret = TREE_OPERAND (ret, 0);
15978   return ret;
15979 }
15980 
15981 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
15982 
15983 static tree
15984 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
15985 		    tree args, tsubst_flags_t complain, tree in_decl)
15986 {
15987   tree new_clauses = NULL_TREE, nc, oc;
15988   tree linear_no_step = NULL_TREE;
15989 
15990   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
15991     {
15992       nc = copy_node (oc);
15993       OMP_CLAUSE_CHAIN (nc) = new_clauses;
15994       new_clauses = nc;
15995 
15996       switch (OMP_CLAUSE_CODE (nc))
15997 	{
15998 	case OMP_CLAUSE_LASTPRIVATE:
15999 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
16000 	    {
16001 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
16002 	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
16003 			   in_decl, /*integral_constant_expression_p=*/false);
16004 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
16005 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
16006 	    }
16007 	  /* FALLTHRU */
16008 	case OMP_CLAUSE_PRIVATE:
16009 	case OMP_CLAUSE_SHARED:
16010 	case OMP_CLAUSE_FIRSTPRIVATE:
16011 	case OMP_CLAUSE_COPYIN:
16012 	case OMP_CLAUSE_COPYPRIVATE:
16013 	case OMP_CLAUSE_UNIFORM:
16014 	case OMP_CLAUSE_DEPEND:
16015 	case OMP_CLAUSE_FROM:
16016 	case OMP_CLAUSE_TO:
16017 	case OMP_CLAUSE_MAP:
16018 	case OMP_CLAUSE_USE_DEVICE_PTR:
16019 	case OMP_CLAUSE_IS_DEVICE_PTR:
16020 	  OMP_CLAUSE_DECL (nc)
16021 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16022 				      in_decl);
16023 	  break;
16024 	case OMP_CLAUSE_TILE:
16025 	case OMP_CLAUSE_IF:
16026 	case OMP_CLAUSE_NUM_THREADS:
16027 	case OMP_CLAUSE_SCHEDULE:
16028 	case OMP_CLAUSE_COLLAPSE:
16029 	case OMP_CLAUSE_FINAL:
16030 	case OMP_CLAUSE_DEVICE:
16031 	case OMP_CLAUSE_DIST_SCHEDULE:
16032 	case OMP_CLAUSE_NUM_TEAMS:
16033 	case OMP_CLAUSE_THREAD_LIMIT:
16034 	case OMP_CLAUSE_SAFELEN:
16035 	case OMP_CLAUSE_SIMDLEN:
16036 	case OMP_CLAUSE_NUM_TASKS:
16037 	case OMP_CLAUSE_GRAINSIZE:
16038 	case OMP_CLAUSE_PRIORITY:
16039 	case OMP_CLAUSE_ORDERED:
16040 	case OMP_CLAUSE_HINT:
16041 	case OMP_CLAUSE_NUM_GANGS:
16042 	case OMP_CLAUSE_NUM_WORKERS:
16043 	case OMP_CLAUSE_VECTOR_LENGTH:
16044 	case OMP_CLAUSE_WORKER:
16045 	case OMP_CLAUSE_VECTOR:
16046 	case OMP_CLAUSE_ASYNC:
16047 	case OMP_CLAUSE_WAIT:
16048 	  OMP_CLAUSE_OPERAND (nc, 0)
16049 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
16050 			   in_decl, /*integral_constant_expression_p=*/false);
16051 	  break;
16052 	case OMP_CLAUSE_REDUCTION:
16053 	  if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
16054 	    {
16055 	      tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
16056 	      if (TREE_CODE (placeholder) == SCOPE_REF)
16057 		{
16058 		  tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
16059 				       complain, in_decl);
16060 		  OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
16061 		    = build_qualified_name (NULL_TREE, scope,
16062 					    TREE_OPERAND (placeholder, 1),
16063 					    false);
16064 		}
16065 	      else
16066 		gcc_assert (identifier_p (placeholder));
16067 	    }
16068 	  OMP_CLAUSE_DECL (nc)
16069 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16070 				      in_decl);
16071 	  break;
16072 	case OMP_CLAUSE_GANG:
16073 	case OMP_CLAUSE_ALIGNED:
16074 	  OMP_CLAUSE_DECL (nc)
16075 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16076 				      in_decl);
16077 	  OMP_CLAUSE_OPERAND (nc, 1)
16078 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
16079 			   in_decl, /*integral_constant_expression_p=*/false);
16080 	  break;
16081 	case OMP_CLAUSE_LINEAR:
16082 	  OMP_CLAUSE_DECL (nc)
16083 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16084 				      in_decl);
16085 	  if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
16086 	    {
16087 	      gcc_assert (!linear_no_step);
16088 	      linear_no_step = nc;
16089 	    }
16090 	  else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
16091 	    OMP_CLAUSE_LINEAR_STEP (nc)
16092 	      = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
16093 					complain, in_decl);
16094 	  else
16095 	    OMP_CLAUSE_LINEAR_STEP (nc)
16096 	      = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
16097 			     in_decl,
16098 			     /*integral_constant_expression_p=*/false);
16099 	  break;
16100 	case OMP_CLAUSE_NOWAIT:
16101 	case OMP_CLAUSE_DEFAULT:
16102 	case OMP_CLAUSE_UNTIED:
16103 	case OMP_CLAUSE_MERGEABLE:
16104 	case OMP_CLAUSE_INBRANCH:
16105 	case OMP_CLAUSE_NOTINBRANCH:
16106 	case OMP_CLAUSE_PROC_BIND:
16107 	case OMP_CLAUSE_FOR:
16108 	case OMP_CLAUSE_PARALLEL:
16109 	case OMP_CLAUSE_SECTIONS:
16110 	case OMP_CLAUSE_TASKGROUP:
16111 	case OMP_CLAUSE_NOGROUP:
16112 	case OMP_CLAUSE_THREADS:
16113 	case OMP_CLAUSE_SIMD:
16114 	case OMP_CLAUSE_DEFAULTMAP:
16115 	case OMP_CLAUSE_INDEPENDENT:
16116 	case OMP_CLAUSE_AUTO:
16117 	case OMP_CLAUSE_SEQ:
16118 	  break;
16119 	default:
16120 	  gcc_unreachable ();
16121 	}
16122       if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
16123 	switch (OMP_CLAUSE_CODE (nc))
16124 	  {
16125 	  case OMP_CLAUSE_SHARED:
16126 	  case OMP_CLAUSE_PRIVATE:
16127 	  case OMP_CLAUSE_FIRSTPRIVATE:
16128 	  case OMP_CLAUSE_LASTPRIVATE:
16129 	  case OMP_CLAUSE_COPYPRIVATE:
16130 	  case OMP_CLAUSE_LINEAR:
16131 	  case OMP_CLAUSE_REDUCTION:
16132 	  case OMP_CLAUSE_USE_DEVICE_PTR:
16133 	  case OMP_CLAUSE_IS_DEVICE_PTR:
16134 	    /* tsubst_expr on SCOPE_REF results in returning
16135 	       finish_non_static_data_member result.  Undo that here.  */
16136 	    if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
16137 		&& (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
16138 		    == IDENTIFIER_NODE))
16139 	      {
16140 		tree t = OMP_CLAUSE_DECL (nc);
16141 		tree v = t;
16142 		while (v)
16143 		  switch (TREE_CODE (v))
16144 		    {
16145 		    case COMPONENT_REF:
16146 		    case MEM_REF:
16147 		    case INDIRECT_REF:
16148 		    CASE_CONVERT:
16149 		    case POINTER_PLUS_EXPR:
16150 		      v = TREE_OPERAND (v, 0);
16151 		      continue;
16152 		    case PARM_DECL:
16153 		      if (DECL_CONTEXT (v) == current_function_decl
16154 			  && DECL_ARTIFICIAL (v)
16155 			  && DECL_NAME (v) == this_identifier)
16156 			OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
16157 		      /* FALLTHRU */
16158 		    default:
16159 		      v = NULL_TREE;
16160 		      break;
16161 		    }
16162 	      }
16163 	    else if (VAR_P (OMP_CLAUSE_DECL (oc))
16164 		     && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
16165 		     && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
16166 		     && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
16167 		     && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
16168 	      {
16169 		tree decl = OMP_CLAUSE_DECL (nc);
16170 		if (VAR_P (decl))
16171 		  {
16172 		    retrofit_lang_decl (decl);
16173 		    DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
16174 		  }
16175 	      }
16176 	    break;
16177 	  default:
16178 	    break;
16179 	  }
16180     }
16181 
16182   new_clauses = nreverse (new_clauses);
16183   if (ort != C_ORT_OMP_DECLARE_SIMD)
16184     {
16185       new_clauses = finish_omp_clauses (new_clauses, ort);
16186       if (linear_no_step)
16187 	for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
16188 	  if (nc == linear_no_step)
16189 	    {
16190 	      OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
16191 	      break;
16192 	    }
16193     }
16194   return new_clauses;
16195 }
16196 
16197 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
16198 
16199 static tree
16200 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
16201 			  tree in_decl)
16202 {
16203 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
16204 
16205   tree purpose, value, chain;
16206 
16207   if (t == NULL)
16208     return t;
16209 
16210   if (TREE_CODE (t) != TREE_LIST)
16211     return tsubst_copy_and_build (t, args, complain, in_decl,
16212 				  /*function_p=*/false,
16213 				  /*integral_constant_expression_p=*/false);
16214 
16215   if (t == void_list_node)
16216     return t;
16217 
16218   purpose = TREE_PURPOSE (t);
16219   if (purpose)
16220     purpose = RECUR (purpose);
16221   value = TREE_VALUE (t);
16222   if (value)
16223     {
16224       if (TREE_CODE (value) != LABEL_DECL)
16225 	value = RECUR (value);
16226       else
16227 	{
16228 	  value = lookup_label (DECL_NAME (value));
16229 	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
16230 	  TREE_USED (value) = 1;
16231 	}
16232     }
16233   chain = TREE_CHAIN (t);
16234   if (chain && chain != void_type_node)
16235     chain = RECUR (chain);
16236   return tree_cons (purpose, value, chain);
16237 #undef RECUR
16238 }
16239 
16240 /* Used to temporarily communicate the list of #pragma omp parallel
16241    clauses to #pragma omp for instantiation if they are combined
16242    together.  */
16243 
16244 static tree *omp_parallel_combined_clauses;
16245 
16246 /* Substitute one OMP_FOR iterator.  */
16247 
16248 static void
16249 tsubst_omp_for_iterator (tree t, int i, tree declv, tree orig_declv,
16250 			 tree initv, tree condv, tree incrv, tree *clauses,
16251 			 tree args, tsubst_flags_t complain, tree in_decl,
16252 			 bool integral_constant_expression_p)
16253 {
16254 #define RECUR(NODE)				\
16255   tsubst_expr ((NODE), args, complain, in_decl,	\
16256 	       integral_constant_expression_p)
16257   tree decl, init, cond, incr;
16258 
16259   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
16260   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
16261 
16262   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
16263     {
16264       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
16265       TREE_VEC_ELT (orig_declv, i) = RECUR (o);
16266     }
16267 
16268   decl = TREE_OPERAND (init, 0);
16269   init = TREE_OPERAND (init, 1);
16270   tree decl_expr = NULL_TREE;
16271   if (init && TREE_CODE (init) == DECL_EXPR)
16272     {
16273       /* We need to jump through some hoops to handle declarations in the
16274 	 init-statement, since we might need to handle auto deduction,
16275 	 but we need to keep control of initialization.  */
16276       decl_expr = init;
16277       init = DECL_INITIAL (DECL_EXPR_DECL (init));
16278       decl = tsubst_decl (decl, args, complain);
16279     }
16280   else
16281     {
16282       if (TREE_CODE (decl) == SCOPE_REF)
16283 	{
16284 	  decl = RECUR (decl);
16285 	  if (TREE_CODE (decl) == COMPONENT_REF)
16286 	    {
16287 	      tree v = decl;
16288 	      while (v)
16289 		switch (TREE_CODE (v))
16290 		  {
16291 		  case COMPONENT_REF:
16292 		  case MEM_REF:
16293 		  case INDIRECT_REF:
16294 		  CASE_CONVERT:
16295 		  case POINTER_PLUS_EXPR:
16296 		    v = TREE_OPERAND (v, 0);
16297 		    continue;
16298 		  case PARM_DECL:
16299 		    if (DECL_CONTEXT (v) == current_function_decl
16300 			&& DECL_ARTIFICIAL (v)
16301 			&& DECL_NAME (v) == this_identifier)
16302 		      {
16303 			decl = TREE_OPERAND (decl, 1);
16304 			decl = omp_privatize_field (decl, false);
16305 		      }
16306 		    /* FALLTHRU */
16307 		  default:
16308 		    v = NULL_TREE;
16309 		    break;
16310 		  }
16311 	    }
16312 	}
16313       else
16314 	decl = RECUR (decl);
16315     }
16316   init = RECUR (init);
16317 
16318   tree auto_node = type_uses_auto (TREE_TYPE (decl));
16319   if (auto_node && init)
16320     TREE_TYPE (decl)
16321       = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
16322 
16323   gcc_assert (!type_dependent_expression_p (decl));
16324 
16325   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
16326     {
16327       if (decl_expr)
16328 	{
16329 	  /* Declare the variable, but don't let that initialize it.  */
16330 	  tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
16331 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
16332 	  RECUR (decl_expr);
16333 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
16334 	}
16335 
16336       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
16337       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16338       if (TREE_CODE (incr) == MODIFY_EXPR)
16339 	{
16340 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16341 	  tree rhs = RECUR (TREE_OPERAND (incr, 1));
16342 	  incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
16343 				      NOP_EXPR, rhs, complain);
16344 	}
16345       else
16346 	incr = RECUR (incr);
16347       TREE_VEC_ELT (declv, i) = decl;
16348       TREE_VEC_ELT (initv, i) = init;
16349       TREE_VEC_ELT (condv, i) = cond;
16350       TREE_VEC_ELT (incrv, i) = incr;
16351       return;
16352     }
16353 
16354   if (decl_expr)
16355     {
16356       /* Declare and initialize the variable.  */
16357       RECUR (decl_expr);
16358       init = NULL_TREE;
16359     }
16360   else if (init)
16361     {
16362       tree *pc;
16363       int j;
16364       for (j = (omp_parallel_combined_clauses == NULL ? 1 : 0); j < 2; j++)
16365 	{
16366 	  for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
16367 	    {
16368 	      if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
16369 		  && OMP_CLAUSE_DECL (*pc) == decl)
16370 		break;
16371 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
16372 		       && OMP_CLAUSE_DECL (*pc) == decl)
16373 		{
16374 		  if (j)
16375 		    break;
16376 		  /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
16377 		  tree c = *pc;
16378 		  *pc = OMP_CLAUSE_CHAIN (c);
16379 		  OMP_CLAUSE_CHAIN (c) = *clauses;
16380 		  *clauses = c;
16381 		}
16382 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
16383 		       && OMP_CLAUSE_DECL (*pc) == decl)
16384 		{
16385 		  error ("iteration variable %qD should not be firstprivate",
16386 			 decl);
16387 		  *pc = OMP_CLAUSE_CHAIN (*pc);
16388 		}
16389 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
16390 		       && OMP_CLAUSE_DECL (*pc) == decl)
16391 		{
16392 		  error ("iteration variable %qD should not be reduction",
16393 			 decl);
16394 		  *pc = OMP_CLAUSE_CHAIN (*pc);
16395 		}
16396 	      else
16397 		pc = &OMP_CLAUSE_CHAIN (*pc);
16398 	    }
16399 	  if (*pc)
16400 	    break;
16401 	}
16402       if (*pc == NULL_TREE)
16403 	{
16404 	  tree c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
16405 	  OMP_CLAUSE_DECL (c) = decl;
16406 	  c = finish_omp_clauses (c, C_ORT_OMP);
16407 	  if (c)
16408 	    {
16409 	      OMP_CLAUSE_CHAIN (c) = *clauses;
16410 	      *clauses = c;
16411 	    }
16412 	}
16413     }
16414   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
16415   if (COMPARISON_CLASS_P (cond))
16416     {
16417       tree op0 = RECUR (TREE_OPERAND (cond, 0));
16418       tree op1 = RECUR (TREE_OPERAND (cond, 1));
16419       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
16420     }
16421   else
16422     cond = RECUR (cond);
16423   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16424   switch (TREE_CODE (incr))
16425     {
16426     case PREINCREMENT_EXPR:
16427     case PREDECREMENT_EXPR:
16428     case POSTINCREMENT_EXPR:
16429     case POSTDECREMENT_EXPR:
16430       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
16431 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
16432       break;
16433     case MODIFY_EXPR:
16434       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16435 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16436 	{
16437 	  tree rhs = TREE_OPERAND (incr, 1);
16438 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16439 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16440 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16441 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16442 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16443 				 rhs0, rhs1));
16444 	}
16445       else
16446 	incr = RECUR (incr);
16447       break;
16448     case MODOP_EXPR:
16449       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16450 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16451 	{
16452 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16453 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16454 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
16455 				 TREE_TYPE (decl), lhs,
16456 				 RECUR (TREE_OPERAND (incr, 2))));
16457 	}
16458       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
16459 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
16460 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
16461 	{
16462 	  tree rhs = TREE_OPERAND (incr, 2);
16463 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16464 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16465 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16466 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16467 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16468 				 rhs0, rhs1));
16469 	}
16470       else
16471 	incr = RECUR (incr);
16472       break;
16473     default:
16474       incr = RECUR (incr);
16475       break;
16476     }
16477 
16478   TREE_VEC_ELT (declv, i) = decl;
16479   TREE_VEC_ELT (initv, i) = init;
16480   TREE_VEC_ELT (condv, i) = cond;
16481   TREE_VEC_ELT (incrv, i) = incr;
16482 #undef RECUR
16483 }
16484 
16485 /* Helper function of tsubst_expr, find OMP_TEAMS inside
16486    of OMP_TARGET's body.  */
16487 
16488 static tree
16489 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
16490 {
16491   *walk_subtrees = 0;
16492   switch (TREE_CODE (*tp))
16493     {
16494     case OMP_TEAMS:
16495       return *tp;
16496     case BIND_EXPR:
16497     case STATEMENT_LIST:
16498       *walk_subtrees = 1;
16499       break;
16500     default:
16501       break;
16502     }
16503   return NULL_TREE;
16504 }
16505 
16506 /* Helper function for tsubst_expr.  For decomposition declaration
16507    artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
16508    also the corresponding decls representing the identifiers
16509    of the decomposition declaration.  Return DECL if successful
16510    or error_mark_node otherwise, set *FIRST to the first decl
16511    in the list chained through DECL_CHAIN and *CNT to the number
16512    of such decls.  */
16513 
16514 static tree
16515 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
16516 		     tsubst_flags_t complain, tree in_decl, tree *first,
16517 		     unsigned int *cnt)
16518 {
16519   tree decl2, decl3, prev = decl;
16520   *cnt = 0;
16521   gcc_assert (DECL_NAME (decl) == NULL_TREE);
16522   for (decl2 = DECL_CHAIN (pattern_decl);
16523        decl2
16524        && VAR_P (decl2)
16525        && DECL_DECOMPOSITION_P (decl2)
16526        && DECL_NAME (decl2);
16527        decl2 = DECL_CHAIN (decl2))
16528     {
16529       if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
16530 	{
16531 	  gcc_assert (errorcount);
16532 	  return error_mark_node;
16533 	}
16534       (*cnt)++;
16535       gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
16536       gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
16537       tree v = DECL_VALUE_EXPR (decl2);
16538       DECL_HAS_VALUE_EXPR_P (decl2) = 0;
16539       SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
16540       decl3 = tsubst (decl2, args, complain, in_decl);
16541       SET_DECL_VALUE_EXPR (decl2, v);
16542       DECL_HAS_VALUE_EXPR_P (decl2) = 1;
16543       if (VAR_P (decl3))
16544 	DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
16545       else
16546 	{
16547 	  gcc_assert (errorcount);
16548 	  decl = error_mark_node;
16549 	  continue;
16550 	}
16551       maybe_push_decl (decl3);
16552       if (error_operand_p (decl3))
16553 	decl = error_mark_node;
16554       else if (decl != error_mark_node
16555 	       && DECL_CHAIN (decl3) != prev
16556 	       && decl != prev)
16557 	{
16558 	  gcc_assert (errorcount);
16559 	  decl = error_mark_node;
16560 	}
16561       else
16562 	prev = decl3;
16563     }
16564   *first = prev;
16565   return decl;
16566 }
16567 
16568 /* Like tsubst_copy for expressions, etc. but also does semantic
16569    processing.  */
16570 
16571 tree
16572 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
16573 	     bool integral_constant_expression_p)
16574 {
16575 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
16576 #define RECUR(NODE)				\
16577   tsubst_expr ((NODE), args, complain, in_decl,	\
16578 	       integral_constant_expression_p)
16579 
16580   tree stmt, tmp;
16581   tree r;
16582   location_t loc;
16583 
16584   if (t == NULL_TREE || t == error_mark_node)
16585     return t;
16586 
16587   loc = input_location;
16588   if (EXPR_HAS_LOCATION (t))
16589     input_location = EXPR_LOCATION (t);
16590   if (STATEMENT_CODE_P (TREE_CODE (t)))
16591     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
16592 
16593   switch (TREE_CODE (t))
16594     {
16595     case STATEMENT_LIST:
16596       {
16597 	tree_stmt_iterator i;
16598 	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
16599 	  RECUR (tsi_stmt (i));
16600 	break;
16601       }
16602 
16603     case CTOR_INITIALIZER:
16604       finish_mem_initializers (tsubst_initializer_list
16605 			       (TREE_OPERAND (t, 0), args));
16606       break;
16607 
16608     case RETURN_EXPR:
16609       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
16610       break;
16611 
16612     case EXPR_STMT:
16613       tmp = RECUR (EXPR_STMT_EXPR (t));
16614       if (EXPR_STMT_STMT_EXPR_RESULT (t))
16615 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
16616       else
16617 	finish_expr_stmt (tmp);
16618       break;
16619 
16620     case USING_STMT:
16621       finish_local_using_directive (USING_STMT_NAMESPACE (t),
16622 				    /*attribs=*/NULL_TREE);
16623       break;
16624 
16625     case DECL_EXPR:
16626       {
16627 	tree decl, pattern_decl;
16628 	tree init;
16629 
16630 	pattern_decl = decl = DECL_EXPR_DECL (t);
16631 	if (TREE_CODE (decl) == LABEL_DECL)
16632 	  finish_label_decl (DECL_NAME (decl));
16633 	else if (TREE_CODE (decl) == USING_DECL)
16634 	  {
16635 	    tree scope = USING_DECL_SCOPE (decl);
16636 	    tree name = DECL_NAME (decl);
16637 
16638 	    scope = tsubst (scope, args, complain, in_decl);
16639 	    decl = lookup_qualified_name (scope, name,
16640 					  /*is_type_p=*/false,
16641 					  /*complain=*/false);
16642 	    if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
16643 	      qualified_name_lookup_error (scope, name, decl, input_location);
16644 	    else
16645 	      finish_local_using_decl (decl, scope, name);
16646 	  }
16647 	else if (is_capture_proxy (decl)
16648 		 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
16649 	  {
16650 	    /* We're in tsubst_lambda_expr, we've already inserted a new
16651 	       capture proxy, so look it up and register it.  */
16652 	    tree inst;
16653 	    if (DECL_PACK_P (decl))
16654 	      {
16655 		inst = (retrieve_local_specialization
16656 			(DECL_CAPTURED_VARIABLE (decl)));
16657 		gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK);
16658 	      }
16659 	    else
16660 	      {
16661 		inst = lookup_name_real (DECL_NAME (decl), 0, 0,
16662 					 /*block_p=*/true, 0, LOOKUP_HIDDEN);
16663 		gcc_assert (inst != decl && is_capture_proxy (inst));
16664 	      }
16665 	    register_local_specialization (inst, decl);
16666 	    break;
16667 	  }
16668 	else if (DECL_IMPLICIT_TYPEDEF_P (decl)
16669 		 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
16670 	  /* Don't copy the old closure; we'll create a new one in
16671 	     tsubst_lambda_expr.  */
16672 	  break;
16673 	else
16674 	  {
16675 	    init = DECL_INITIAL (decl);
16676 	    decl = tsubst (decl, args, complain, in_decl);
16677 	    if (decl != error_mark_node)
16678 	      {
16679 		/* By marking the declaration as instantiated, we avoid
16680 		   trying to instantiate it.  Since instantiate_decl can't
16681 		   handle local variables, and since we've already done
16682 		   all that needs to be done, that's the right thing to
16683 		   do.  */
16684 		if (VAR_P (decl))
16685 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
16686 		if (VAR_P (decl)
16687 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
16688 		  /* Anonymous aggregates are a special case.  */
16689 		  finish_anon_union (decl);
16690 		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
16691 		  {
16692 		    DECL_CONTEXT (decl) = current_function_decl;
16693 		    if (DECL_NAME (decl) == this_identifier)
16694 		      {
16695 			tree lam = DECL_CONTEXT (current_function_decl);
16696 			lam = CLASSTYPE_LAMBDA_EXPR (lam);
16697 			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
16698 		      }
16699 		    insert_capture_proxy (decl);
16700 		  }
16701 		else if (DECL_IMPLICIT_TYPEDEF_P (t))
16702 		  /* We already did a pushtag.  */;
16703 		else if (TREE_CODE (decl) == FUNCTION_DECL
16704 			 && DECL_OMP_DECLARE_REDUCTION_P (decl)
16705 			 && DECL_FUNCTION_SCOPE_P (pattern_decl))
16706 		  {
16707 		    DECL_CONTEXT (decl) = NULL_TREE;
16708 		    pushdecl (decl);
16709 		    DECL_CONTEXT (decl) = current_function_decl;
16710 		    cp_check_omp_declare_reduction (decl);
16711 		  }
16712 		else
16713 		  {
16714 		    int const_init = false;
16715 		    maybe_push_decl (decl);
16716 		    if (VAR_P (decl)
16717 			&& DECL_PRETTY_FUNCTION_P (decl))
16718 		      {
16719 			/* For __PRETTY_FUNCTION__ we have to adjust the
16720 			   initializer.  */
16721 			const char *const name
16722 			  = cxx_printable_name (current_function_decl, 2);
16723 			init = cp_fname_init (name, &TREE_TYPE (decl));
16724 		      }
16725 		    else
16726 		      init = tsubst_init (init, decl, args, complain, in_decl);
16727 
16728 		    if (VAR_P (decl))
16729 		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
16730 				    (pattern_decl));
16731 		    if (VAR_P (decl)
16732 			&& DECL_DECOMPOSITION_P (decl)
16733 			&& TREE_TYPE (pattern_decl) != error_mark_node)
16734 		      {
16735 			unsigned int cnt;
16736 			tree first;
16737 			tree ndecl
16738 			  = tsubst_decomp_names (decl, pattern_decl, args,
16739 						 complain, in_decl, &first, &cnt);
16740 			if (ndecl != error_mark_node)
16741 			  cp_maybe_mangle_decomp (ndecl, first, cnt);
16742 			cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
16743 			if (ndecl != error_mark_node)
16744 			  cp_finish_decomp (ndecl, first, cnt);
16745 		      }
16746 		    else
16747 		      cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
16748 		  }
16749 	      }
16750 	  }
16751 
16752 	break;
16753       }
16754 
16755     case FOR_STMT:
16756       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
16757       RECUR (FOR_INIT_STMT (t));
16758       finish_init_stmt (stmt);
16759       tmp = RECUR (FOR_COND (t));
16760       finish_for_cond (tmp, stmt, false, 0);
16761       tmp = RECUR (FOR_EXPR (t));
16762       finish_for_expr (tmp, stmt);
16763       {
16764 	bool prev = note_iteration_stmt_body_start ();
16765 	RECUR (FOR_BODY (t));
16766 	note_iteration_stmt_body_end (prev);
16767       }
16768       finish_for_stmt (stmt);
16769       break;
16770 
16771     case RANGE_FOR_STMT:
16772       {
16773 	/* Construct another range_for, if this is not a final
16774 	   substitution (for inside inside a generic lambda of a
16775 	   template).  Otherwise convert to a regular for.  */
16776         tree decl, expr;
16777         stmt = (processing_template_decl
16778 		? begin_range_for_stmt (NULL_TREE, NULL_TREE)
16779 		: begin_for_stmt (NULL_TREE, NULL_TREE));
16780         decl = RANGE_FOR_DECL (t);
16781         decl = tsubst (decl, args, complain, in_decl);
16782         maybe_push_decl (decl);
16783         expr = RECUR (RANGE_FOR_EXPR (t));
16784 
16785 	tree decomp_first = NULL_TREE;
16786 	unsigned decomp_cnt = 0;
16787 	if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
16788 	  decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
16789 				      complain, in_decl,
16790 				      &decomp_first, &decomp_cnt);
16791 
16792 	if (processing_template_decl)
16793 	  {
16794 	    RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
16795 	    RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
16796 	    finish_range_for_decl (stmt, decl, expr);
16797 	  }
16798 	else
16799 	  {
16800 	    unsigned short unroll = (RANGE_FOR_UNROLL (t)
16801 				     ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
16802 	    stmt = cp_convert_range_for (stmt, decl, expr,
16803 					 decomp_first, decomp_cnt,
16804 					 RANGE_FOR_IVDEP (t), unroll);
16805 	  }
16806 
16807 	bool prev = note_iteration_stmt_body_start ();
16808         RECUR (RANGE_FOR_BODY (t));
16809 	note_iteration_stmt_body_end (prev);
16810         finish_for_stmt (stmt);
16811       }
16812       break;
16813 
16814     case WHILE_STMT:
16815       stmt = begin_while_stmt ();
16816       tmp = RECUR (WHILE_COND (t));
16817       finish_while_stmt_cond (tmp, stmt, false, 0);
16818       {
16819 	bool prev = note_iteration_stmt_body_start ();
16820 	RECUR (WHILE_BODY (t));
16821 	note_iteration_stmt_body_end (prev);
16822       }
16823       finish_while_stmt (stmt);
16824       break;
16825 
16826     case DO_STMT:
16827       stmt = begin_do_stmt ();
16828       {
16829 	bool prev = note_iteration_stmt_body_start ();
16830 	RECUR (DO_BODY (t));
16831 	note_iteration_stmt_body_end (prev);
16832       }
16833       finish_do_body (stmt);
16834       tmp = RECUR (DO_COND (t));
16835       finish_do_stmt (tmp, stmt, false, 0);
16836       break;
16837 
16838     case IF_STMT:
16839       stmt = begin_if_stmt ();
16840       IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
16841       if (IF_STMT_CONSTEXPR_P (t))
16842 	args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args);
16843       tmp = RECUR (IF_COND (t));
16844       tmp = finish_if_stmt_cond (tmp, stmt);
16845       if (IF_STMT_CONSTEXPR_P (t)
16846 	  && instantiation_dependent_expression_p (tmp))
16847 	{
16848 	  /* We're partially instantiating a generic lambda, but the condition
16849 	     of the constexpr if is still dependent.  Don't substitute into the
16850 	     branches now, just remember the template arguments.  */
16851 	  do_poplevel (IF_SCOPE (stmt));
16852 	  IF_COND (stmt) = IF_COND (t);
16853 	  THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
16854 	  ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
16855 	  IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
16856 	  add_stmt (stmt);
16857 	  break;
16858 	}
16859       if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
16860 	/* Don't instantiate the THEN_CLAUSE. */;
16861       else
16862 	{
16863 	  bool inhibit = integer_zerop (fold_non_dependent_expr (tmp));
16864 	  if (inhibit)
16865 	    ++c_inhibit_evaluation_warnings;
16866 	  RECUR (THEN_CLAUSE (t));
16867 	  if (inhibit)
16868 	    --c_inhibit_evaluation_warnings;
16869 	}
16870       finish_then_clause (stmt);
16871 
16872       if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
16873 	/* Don't instantiate the ELSE_CLAUSE. */;
16874       else if (ELSE_CLAUSE (t))
16875 	{
16876 	  bool inhibit = integer_nonzerop (fold_non_dependent_expr (tmp));
16877 	  begin_else_clause (stmt);
16878 	  if (inhibit)
16879 	    ++c_inhibit_evaluation_warnings;
16880 	  RECUR (ELSE_CLAUSE (t));
16881 	  if (inhibit)
16882 	    --c_inhibit_evaluation_warnings;
16883 	  finish_else_clause (stmt);
16884 	}
16885 
16886       finish_if_stmt (stmt);
16887       break;
16888 
16889     case BIND_EXPR:
16890       if (BIND_EXPR_BODY_BLOCK (t))
16891 	stmt = begin_function_body ();
16892       else
16893 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
16894 				    ? BCS_TRY_BLOCK : 0);
16895 
16896       RECUR (BIND_EXPR_BODY (t));
16897 
16898       if (BIND_EXPR_BODY_BLOCK (t))
16899 	finish_function_body (stmt);
16900       else
16901 	finish_compound_stmt (stmt);
16902       break;
16903 
16904     case BREAK_STMT:
16905       finish_break_stmt ();
16906       break;
16907 
16908     case CONTINUE_STMT:
16909       finish_continue_stmt ();
16910       break;
16911 
16912     case SWITCH_STMT:
16913       stmt = begin_switch_stmt ();
16914       tmp = RECUR (SWITCH_STMT_COND (t));
16915       finish_switch_cond (tmp, stmt);
16916       RECUR (SWITCH_STMT_BODY (t));
16917       finish_switch_stmt (stmt);
16918       break;
16919 
16920     case CASE_LABEL_EXPR:
16921       {
16922 	tree low = RECUR (CASE_LOW (t));
16923 	tree high = RECUR (CASE_HIGH (t));
16924 	tree l = finish_case_label (EXPR_LOCATION (t), low, high);
16925 	if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
16926 	  FALLTHROUGH_LABEL_P (CASE_LABEL (l))
16927 	    = FALLTHROUGH_LABEL_P (CASE_LABEL (t));
16928       }
16929       break;
16930 
16931     case LABEL_EXPR:
16932       {
16933 	tree decl = LABEL_EXPR_LABEL (t);
16934 	tree label;
16935 
16936 	label = finish_label_stmt (DECL_NAME (decl));
16937 	if (TREE_CODE (label) == LABEL_DECL)
16938 	  FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
16939 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
16940 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
16941       }
16942       break;
16943 
16944     case GOTO_EXPR:
16945       tmp = GOTO_DESTINATION (t);
16946       if (TREE_CODE (tmp) != LABEL_DECL)
16947 	/* Computed goto's must be tsubst'd into.  On the other hand,
16948 	   non-computed gotos must not be; the identifier in question
16949 	   will have no binding.  */
16950 	tmp = RECUR (tmp);
16951       else
16952 	tmp = DECL_NAME (tmp);
16953       finish_goto_stmt (tmp);
16954       break;
16955 
16956     case ASM_EXPR:
16957       {
16958 	tree string = RECUR (ASM_STRING (t));
16959 	tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
16960 						 complain, in_decl);
16961 	tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
16962 						complain, in_decl);
16963 	tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
16964 	 					  complain, in_decl);
16965 	tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
16966 						complain, in_decl);
16967 	tmp = finish_asm_stmt (ASM_VOLATILE_P (t), string, outputs, inputs,
16968 			       clobbers, labels);
16969 	tree asm_expr = tmp;
16970 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
16971 	  asm_expr = TREE_OPERAND (asm_expr, 0);
16972 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
16973       }
16974       break;
16975 
16976     case TRY_BLOCK:
16977       if (CLEANUP_P (t))
16978 	{
16979 	  stmt = begin_try_block ();
16980 	  RECUR (TRY_STMTS (t));
16981 	  finish_cleanup_try_block (stmt);
16982 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
16983 	}
16984       else
16985 	{
16986 	  tree compound_stmt = NULL_TREE;
16987 
16988 	  if (FN_TRY_BLOCK_P (t))
16989 	    stmt = begin_function_try_block (&compound_stmt);
16990 	  else
16991 	    stmt = begin_try_block ();
16992 
16993 	  RECUR (TRY_STMTS (t));
16994 
16995 	  if (FN_TRY_BLOCK_P (t))
16996 	    finish_function_try_block (stmt);
16997 	  else
16998 	    finish_try_block (stmt);
16999 
17000 	  RECUR (TRY_HANDLERS (t));
17001 	  if (FN_TRY_BLOCK_P (t))
17002 	    finish_function_handler_sequence (stmt, compound_stmt);
17003 	  else
17004 	    finish_handler_sequence (stmt);
17005 	}
17006       break;
17007 
17008     case HANDLER:
17009       {
17010 	tree decl = HANDLER_PARMS (t);
17011 
17012 	if (decl)
17013 	  {
17014 	    decl = tsubst (decl, args, complain, in_decl);
17015 	    /* Prevent instantiate_decl from trying to instantiate
17016 	       this variable.  We've already done all that needs to be
17017 	       done.  */
17018 	    if (decl != error_mark_node)
17019 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
17020 	  }
17021 	stmt = begin_handler ();
17022 	finish_handler_parms (decl, stmt);
17023 	RECUR (HANDLER_BODY (t));
17024 	finish_handler (stmt);
17025       }
17026       break;
17027 
17028     case TAG_DEFN:
17029       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
17030       if (CLASS_TYPE_P (tmp))
17031 	{
17032 	  /* Local classes are not independent templates; they are
17033 	     instantiated along with their containing function.  And this
17034 	     way we don't have to deal with pushing out of one local class
17035 	     to instantiate a member of another local class.  */
17036 	  /* Closures are handled by the LAMBDA_EXPR.  */
17037 	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
17038 	  complete_type (tmp);
17039 	  for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
17040 	    if ((VAR_P (fld)
17041 		 || (TREE_CODE (fld) == FUNCTION_DECL
17042 		     && !DECL_ARTIFICIAL (fld)))
17043 		&& DECL_TEMPLATE_INSTANTIATION (fld))
17044 	      instantiate_decl (fld, /*defer_ok=*/false,
17045 				/*expl_inst_class=*/false);
17046 	}
17047       break;
17048 
17049     case STATIC_ASSERT:
17050       {
17051 	tree condition;
17052 
17053 	++c_inhibit_evaluation_warnings;
17054         condition =
17055           tsubst_expr (STATIC_ASSERT_CONDITION (t),
17056                        args,
17057                        complain, in_decl,
17058                        /*integral_constant_expression_p=*/true);
17059 	--c_inhibit_evaluation_warnings;
17060 
17061         finish_static_assert (condition,
17062                               STATIC_ASSERT_MESSAGE (t),
17063                               STATIC_ASSERT_SOURCE_LOCATION (t),
17064                               /*member_p=*/false);
17065       }
17066       break;
17067 
17068     case OACC_KERNELS:
17069     case OACC_PARALLEL:
17070       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
17071 				in_decl);
17072       stmt = begin_omp_parallel ();
17073       RECUR (OMP_BODY (t));
17074       finish_omp_construct (TREE_CODE (t), stmt, tmp);
17075       break;
17076 
17077     case OMP_PARALLEL:
17078       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
17079       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
17080 				complain, in_decl);
17081       if (OMP_PARALLEL_COMBINED (t))
17082 	omp_parallel_combined_clauses = &tmp;
17083       stmt = begin_omp_parallel ();
17084       RECUR (OMP_PARALLEL_BODY (t));
17085       gcc_assert (omp_parallel_combined_clauses == NULL);
17086       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
17087 	= OMP_PARALLEL_COMBINED (t);
17088       pop_omp_privatization_clauses (r);
17089       break;
17090 
17091     case OMP_TASK:
17092       r = push_omp_privatization_clauses (false);
17093       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
17094 				complain, in_decl);
17095       stmt = begin_omp_task ();
17096       RECUR (OMP_TASK_BODY (t));
17097       finish_omp_task (tmp, stmt);
17098       pop_omp_privatization_clauses (r);
17099       break;
17100 
17101     case OMP_FOR:
17102     case OMP_SIMD:
17103     case OMP_DISTRIBUTE:
17104     case OMP_TASKLOOP:
17105     case OACC_LOOP:
17106       {
17107 	tree clauses, body, pre_body;
17108 	tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
17109 	tree orig_declv = NULL_TREE;
17110 	tree incrv = NULL_TREE;
17111 	enum c_omp_region_type ort = C_ORT_OMP;
17112 	int i;
17113 
17114 	if (TREE_CODE (t) == OACC_LOOP)
17115 	  ort = C_ORT_ACC;
17116 
17117 	r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
17118 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
17119 				      in_decl);
17120 	if (OMP_FOR_INIT (t) != NULL_TREE)
17121 	  {
17122 	    declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17123 	    if (OMP_FOR_ORIG_DECLS (t))
17124 	      orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17125 	    initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17126 	    condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17127 	    incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17128 	  }
17129 
17130 	stmt = begin_omp_structured_block ();
17131 
17132 	pre_body = push_stmt_list ();
17133 	RECUR (OMP_FOR_PRE_BODY (t));
17134 	pre_body = pop_stmt_list (pre_body);
17135 
17136 	if (OMP_FOR_INIT (t) != NULL_TREE)
17137 	  for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
17138 	    tsubst_omp_for_iterator (t, i, declv, orig_declv, initv, condv,
17139 				     incrv, &clauses, args, complain, in_decl,
17140 				     integral_constant_expression_p);
17141 	omp_parallel_combined_clauses = NULL;
17142 
17143 	body = push_stmt_list ();
17144 	RECUR (OMP_FOR_BODY (t));
17145 	body = pop_stmt_list (body);
17146 
17147 	if (OMP_FOR_INIT (t) != NULL_TREE)
17148 	  t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
17149 			      orig_declv, initv, condv, incrv, body, pre_body,
17150 			      NULL, clauses);
17151 	else
17152 	  {
17153 	    t = make_node (TREE_CODE (t));
17154 	    TREE_TYPE (t) = void_type_node;
17155 	    OMP_FOR_BODY (t) = body;
17156 	    OMP_FOR_PRE_BODY (t) = pre_body;
17157 	    OMP_FOR_CLAUSES (t) = clauses;
17158 	    SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
17159 	    add_stmt (t);
17160 	  }
17161 
17162 	add_stmt (finish_omp_structured_block (stmt));
17163 	pop_omp_privatization_clauses (r);
17164       }
17165       break;
17166 
17167     case OMP_SECTIONS:
17168       omp_parallel_combined_clauses = NULL;
17169       /* FALLTHRU */
17170     case OMP_SINGLE:
17171     case OMP_TEAMS:
17172     case OMP_CRITICAL:
17173       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
17174 					  && OMP_TEAMS_COMBINED (t));
17175       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
17176 				in_decl);
17177       stmt = push_stmt_list ();
17178       RECUR (OMP_BODY (t));
17179       stmt = pop_stmt_list (stmt);
17180 
17181       t = copy_node (t);
17182       OMP_BODY (t) = stmt;
17183       OMP_CLAUSES (t) = tmp;
17184       add_stmt (t);
17185       pop_omp_privatization_clauses (r);
17186       break;
17187 
17188     case OACC_DATA:
17189     case OMP_TARGET_DATA:
17190     case OMP_TARGET:
17191       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
17192 				? C_ORT_ACC : C_ORT_OMP, args, complain,
17193 				in_decl);
17194       keep_next_level (true);
17195       stmt = begin_omp_structured_block ();
17196 
17197       RECUR (OMP_BODY (t));
17198       stmt = finish_omp_structured_block (stmt);
17199 
17200       t = copy_node (t);
17201       OMP_BODY (t) = stmt;
17202       OMP_CLAUSES (t) = tmp;
17203       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
17204 	{
17205 	  tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
17206 	  if (teams)
17207 	    {
17208 	      /* For combined target teams, ensure the num_teams and
17209 		 thread_limit clause expressions are evaluated on the host,
17210 		 before entering the target construct.  */
17211 	      tree c;
17212 	      for (c = OMP_TEAMS_CLAUSES (teams);
17213 		   c; c = OMP_CLAUSE_CHAIN (c))
17214 		if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
17215 		     || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
17216 		    && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
17217 		  {
17218 		    tree expr = OMP_CLAUSE_OPERAND (c, 0);
17219 		    expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
17220 		    if (expr == error_mark_node)
17221 		      continue;
17222 		    tmp = TARGET_EXPR_SLOT (expr);
17223 		    add_stmt (expr);
17224 		    OMP_CLAUSE_OPERAND (c, 0) = expr;
17225 		    tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
17226 						OMP_CLAUSE_FIRSTPRIVATE);
17227 		    OMP_CLAUSE_DECL (tc) = tmp;
17228 		    OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
17229 		    OMP_TARGET_CLAUSES (t) = tc;
17230 		  }
17231 	    }
17232 	}
17233       add_stmt (t);
17234       break;
17235 
17236     case OACC_DECLARE:
17237       t = copy_node (t);
17238       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
17239 				complain, in_decl);
17240       OACC_DECLARE_CLAUSES (t) = tmp;
17241       add_stmt (t);
17242       break;
17243 
17244     case OMP_TARGET_UPDATE:
17245     case OMP_TARGET_ENTER_DATA:
17246     case OMP_TARGET_EXIT_DATA:
17247       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
17248 				complain, in_decl);
17249       t = copy_node (t);
17250       OMP_STANDALONE_CLAUSES (t) = tmp;
17251       add_stmt (t);
17252       break;
17253 
17254     case OACC_ENTER_DATA:
17255     case OACC_EXIT_DATA:
17256     case OACC_UPDATE:
17257       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
17258 				complain, in_decl);
17259       t = copy_node (t);
17260       OMP_STANDALONE_CLAUSES (t) = tmp;
17261       add_stmt (t);
17262       break;
17263 
17264     case OMP_ORDERED:
17265       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
17266 				complain, in_decl);
17267       stmt = push_stmt_list ();
17268       RECUR (OMP_BODY (t));
17269       stmt = pop_stmt_list (stmt);
17270 
17271       t = copy_node (t);
17272       OMP_BODY (t) = stmt;
17273       OMP_ORDERED_CLAUSES (t) = tmp;
17274       add_stmt (t);
17275       break;
17276 
17277     case OMP_SECTION:
17278     case OMP_MASTER:
17279     case OMP_TASKGROUP:
17280       stmt = push_stmt_list ();
17281       RECUR (OMP_BODY (t));
17282       stmt = pop_stmt_list (stmt);
17283 
17284       t = copy_node (t);
17285       OMP_BODY (t) = stmt;
17286       add_stmt (t);
17287       break;
17288 
17289     case OMP_ATOMIC:
17290       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
17291       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
17292 	{
17293 	  tree op1 = TREE_OPERAND (t, 1);
17294 	  tree rhs1 = NULL_TREE;
17295 	  tree lhs, rhs;
17296 	  if (TREE_CODE (op1) == COMPOUND_EXPR)
17297 	    {
17298 	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
17299 	      op1 = TREE_OPERAND (op1, 1);
17300 	    }
17301 	  lhs = RECUR (TREE_OPERAND (op1, 0));
17302 	  rhs = RECUR (TREE_OPERAND (op1, 1));
17303 	  finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
17304 			     NULL_TREE, NULL_TREE, rhs1,
17305 			     OMP_ATOMIC_SEQ_CST (t));
17306 	}
17307       else
17308 	{
17309 	  tree op1 = TREE_OPERAND (t, 1);
17310 	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
17311 	  tree rhs1 = NULL_TREE;
17312 	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
17313 	  enum tree_code opcode = NOP_EXPR;
17314 	  if (code == OMP_ATOMIC_READ)
17315 	    {
17316 	      v = RECUR (TREE_OPERAND (op1, 0));
17317 	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
17318 	    }
17319 	  else if (code == OMP_ATOMIC_CAPTURE_OLD
17320 		   || code == OMP_ATOMIC_CAPTURE_NEW)
17321 	    {
17322 	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
17323 	      v = RECUR (TREE_OPERAND (op1, 0));
17324 	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
17325 	      if (TREE_CODE (op11) == COMPOUND_EXPR)
17326 		{
17327 		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
17328 		  op11 = TREE_OPERAND (op11, 1);
17329 		}
17330 	      lhs = RECUR (TREE_OPERAND (op11, 0));
17331 	      rhs = RECUR (TREE_OPERAND (op11, 1));
17332 	      opcode = TREE_CODE (op11);
17333 	      if (opcode == MODIFY_EXPR)
17334 		opcode = NOP_EXPR;
17335 	    }
17336 	  else
17337 	    {
17338 	      code = OMP_ATOMIC;
17339 	      lhs = RECUR (TREE_OPERAND (op1, 0));
17340 	      rhs = RECUR (TREE_OPERAND (op1, 1));
17341 	    }
17342 	  finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1,
17343 			     OMP_ATOMIC_SEQ_CST (t));
17344 	}
17345       break;
17346 
17347     case TRANSACTION_EXPR:
17348       {
17349 	int flags = 0;
17350 	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
17351 	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
17352 
17353         if (TRANSACTION_EXPR_IS_STMT (t))
17354           {
17355 	    tree body = TRANSACTION_EXPR_BODY (t);
17356 	    tree noex = NULL_TREE;
17357 	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
17358 	      {
17359 		noex = MUST_NOT_THROW_COND (body);
17360 		if (noex == NULL_TREE)
17361 		  noex = boolean_true_node;
17362 		body = TREE_OPERAND (body, 0);
17363 	      }
17364             stmt = begin_transaction_stmt (input_location, NULL, flags);
17365             RECUR (body);
17366             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
17367           }
17368         else
17369           {
17370             stmt = build_transaction_expr (EXPR_LOCATION (t),
17371 					   RECUR (TRANSACTION_EXPR_BODY (t)),
17372 					   flags, NULL_TREE);
17373             RETURN (stmt);
17374           }
17375       }
17376       break;
17377 
17378     case MUST_NOT_THROW_EXPR:
17379       {
17380 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17381 	tree cond = RECUR (MUST_NOT_THROW_COND (t));
17382 	RETURN (build_must_not_throw_expr (op0, cond));
17383       }
17384 
17385     case EXPR_PACK_EXPANSION:
17386       error ("invalid use of pack expansion expression");
17387       RETURN (error_mark_node);
17388 
17389     case NONTYPE_ARGUMENT_PACK:
17390       error ("use %<...%> to expand argument pack");
17391       RETURN (error_mark_node);
17392 
17393     case COMPOUND_EXPR:
17394       tmp = RECUR (TREE_OPERAND (t, 0));
17395       if (tmp == NULL_TREE)
17396 	/* If the first operand was a statement, we're done with it.  */
17397 	RETURN (RECUR (TREE_OPERAND (t, 1)));
17398       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
17399 				    RECUR (TREE_OPERAND (t, 1)),
17400 				    complain));
17401 
17402     case ANNOTATE_EXPR:
17403       tmp = RECUR (TREE_OPERAND (t, 0));
17404       RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
17405 			  TREE_TYPE (tmp), tmp,
17406 			  RECUR (TREE_OPERAND (t, 1)),
17407 			  RECUR (TREE_OPERAND (t, 2))));
17408 
17409     default:
17410       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
17411 
17412       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
17413 				    /*function_p=*/false,
17414 				    integral_constant_expression_p));
17415     }
17416 
17417   RETURN (NULL_TREE);
17418  out:
17419   input_location = loc;
17420   return r;
17421 #undef RECUR
17422 #undef RETURN
17423 }
17424 
17425 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
17426    function.  For description of the body see comment above
17427    cp_parser_omp_declare_reduction_exprs.  */
17428 
17429 static void
17430 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17431 {
17432   if (t == NULL_TREE || t == error_mark_node)
17433     return;
17434 
17435   gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
17436 
17437   tree_stmt_iterator tsi;
17438   int i;
17439   tree stmts[7];
17440   memset (stmts, 0, sizeof stmts);
17441   for (i = 0, tsi = tsi_start (t);
17442        i < 7 && !tsi_end_p (tsi);
17443        i++, tsi_next (&tsi))
17444     stmts[i] = tsi_stmt (tsi);
17445   gcc_assert (tsi_end_p (tsi));
17446 
17447   if (i >= 3)
17448     {
17449       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
17450 		  && TREE_CODE (stmts[1]) == DECL_EXPR);
17451       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
17452 			     args, complain, in_decl);
17453       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
17454 			    args, complain, in_decl);
17455       DECL_CONTEXT (omp_out) = current_function_decl;
17456       DECL_CONTEXT (omp_in) = current_function_decl;
17457       keep_next_level (true);
17458       tree block = begin_omp_structured_block ();
17459       tsubst_expr (stmts[2], args, complain, in_decl, false);
17460       block = finish_omp_structured_block (block);
17461       block = maybe_cleanup_point_expr_void (block);
17462       add_decl_expr (omp_out);
17463       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
17464 	TREE_NO_WARNING (omp_out) = 1;
17465       add_decl_expr (omp_in);
17466       finish_expr_stmt (block);
17467     }
17468   if (i >= 6)
17469     {
17470       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
17471 		  && TREE_CODE (stmts[4]) == DECL_EXPR);
17472       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
17473 			      args, complain, in_decl);
17474       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
17475 			      args, complain, in_decl);
17476       DECL_CONTEXT (omp_priv) = current_function_decl;
17477       DECL_CONTEXT (omp_orig) = current_function_decl;
17478       keep_next_level (true);
17479       tree block = begin_omp_structured_block ();
17480       tsubst_expr (stmts[5], args, complain, in_decl, false);
17481       block = finish_omp_structured_block (block);
17482       block = maybe_cleanup_point_expr_void (block);
17483       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
17484       add_decl_expr (omp_priv);
17485       add_decl_expr (omp_orig);
17486       finish_expr_stmt (block);
17487       if (i == 7)
17488 	add_decl_expr (omp_orig);
17489     }
17490 }
17491 
17492 /* T is a postfix-expression that is not being used in a function
17493    call.  Return the substituted version of T.  */
17494 
17495 static tree
17496 tsubst_non_call_postfix_expression (tree t, tree args,
17497 				    tsubst_flags_t complain,
17498 				    tree in_decl)
17499 {
17500   if (TREE_CODE (t) == SCOPE_REF)
17501     t = tsubst_qualified_id (t, args, complain, in_decl,
17502 			     /*done=*/false, /*address_p=*/false);
17503   else
17504     t = tsubst_copy_and_build (t, args, complain, in_decl,
17505 			       /*function_p=*/false,
17506 			       /*integral_constant_expression_p=*/false);
17507 
17508   return t;
17509 }
17510 
17511 /* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
17512    instantiation context.  Instantiating a pack expansion containing a lambda
17513    might result in multiple lambdas all based on the same lambda in the
17514    template.  */
17515 
17516 tree
17517 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17518 {
17519   tree oldfn = lambda_function (t);
17520   in_decl = oldfn;
17521 
17522   tree r = build_lambda_expr ();
17523 
17524   LAMBDA_EXPR_LOCATION (r)
17525     = LAMBDA_EXPR_LOCATION (t);
17526   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
17527     = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
17528   LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
17529 
17530   if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
17531     LAMBDA_EXPR_EXTRA_SCOPE (r) = NULL_TREE;
17532   else
17533     record_lambda_scope (r);
17534 
17535   gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
17536 	      && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
17537 
17538   for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
17539        cap = TREE_CHAIN (cap))
17540     {
17541       tree field = TREE_PURPOSE (cap);
17542       if (PACK_EXPANSION_P (field))
17543 	field = PACK_EXPANSION_PATTERN (field);
17544       field = tsubst_decl (field, args, complain);
17545 
17546       if (field == error_mark_node)
17547 	return error_mark_node;
17548 
17549       tree init = TREE_VALUE (cap);
17550       if (PACK_EXPANSION_P (init))
17551 	init = tsubst_pack_expansion (init, args, complain, in_decl);
17552       else
17553 	init = tsubst_copy_and_build (init, args, complain, in_decl,
17554 				      /*fn*/false, /*constexpr*/false);
17555 
17556       if (TREE_CODE (field) == TREE_VEC)
17557 	{
17558 	  int len = TREE_VEC_LENGTH (field);
17559 	  gcc_assert (TREE_CODE (init) == TREE_VEC
17560 		      && TREE_VEC_LENGTH (init) == len);
17561 	  for (int i = 0; i < len; ++i)
17562 	    LAMBDA_EXPR_CAPTURE_LIST (r)
17563 	      = tree_cons (TREE_VEC_ELT (field, i),
17564 			   TREE_VEC_ELT (init, i),
17565 			   LAMBDA_EXPR_CAPTURE_LIST (r));
17566 	}
17567       else
17568 	{
17569 	  LAMBDA_EXPR_CAPTURE_LIST (r)
17570 	    = tree_cons (field, init, LAMBDA_EXPR_CAPTURE_LIST (r));
17571 
17572 	  if (id_equal (DECL_NAME (field), "__this"))
17573 	    LAMBDA_EXPR_THIS_CAPTURE (r) = field;
17574 	}
17575     }
17576 
17577   tree type = begin_lambda_type (r);
17578   if (type == error_mark_node)
17579     return error_mark_node;
17580 
17581   /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
17582   determine_visibility (TYPE_NAME (type));
17583 
17584   register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
17585 
17586   tree oldtmpl = (generic_lambda_fn_p (oldfn)
17587 		  ? DECL_TI_TEMPLATE (oldfn)
17588 		  : NULL_TREE);
17589 
17590   tree fntype = static_fn_type (oldfn);
17591   if (oldtmpl)
17592     ++processing_template_decl;
17593   fntype = tsubst (fntype, args, complain, in_decl);
17594   if (oldtmpl)
17595     --processing_template_decl;
17596 
17597   if (fntype == error_mark_node)
17598     r = error_mark_node;
17599   else
17600     {
17601       /* Fix the type of 'this'.  */
17602       fntype = build_memfn_type (fntype, type,
17603 				 type_memfn_quals (fntype),
17604 				 type_memfn_rqual (fntype));
17605       tree fn, tmpl;
17606       if (oldtmpl)
17607 	{
17608 	  tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
17609 	  fn = DECL_TEMPLATE_RESULT (tmpl);
17610 	  finish_member_declaration (tmpl);
17611 	}
17612       else
17613 	{
17614 	  tmpl = NULL_TREE;
17615 	  fn = tsubst_function_decl (oldfn, args, complain, fntype);
17616 	  finish_member_declaration (fn);
17617 	}
17618 
17619       /* Let finish_function set this.  */
17620       DECL_DECLARED_CONSTEXPR_P (fn) = false;
17621 
17622       bool nested = cfun;
17623       if (nested)
17624 	push_function_context ();
17625       else
17626 	/* Still increment function_depth so that we don't GC in the
17627 	   middle of an expression.  */
17628 	++function_depth;
17629 
17630       local_specialization_stack s (lss_copy);
17631 
17632       tree body = start_lambda_function (fn, r);
17633 
17634       register_parameter_specializations (oldfn, fn);
17635 
17636       tsubst_expr (DECL_SAVED_TREE (oldfn), args, complain, r,
17637 		   /*constexpr*/false);
17638 
17639       finish_lambda_function (body);
17640 
17641       if (nested)
17642 	pop_function_context ();
17643       else
17644 	--function_depth;
17645 
17646       /* The capture list was built up in reverse order; fix that now.  */
17647       LAMBDA_EXPR_CAPTURE_LIST (r)
17648 	= nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
17649 
17650       LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
17651 
17652       maybe_add_lambda_conv_op (type);
17653     }
17654 
17655   finish_struct (type, /*attr*/NULL_TREE);
17656 
17657   insert_pending_capture_proxies ();
17658 
17659   return r;
17660 }
17661 
17662 /* Like tsubst but deals with expressions and performs semantic
17663    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
17664 
17665 tree
17666 tsubst_copy_and_build (tree t,
17667 		       tree args,
17668 		       tsubst_flags_t complain,
17669 		       tree in_decl,
17670 		       bool function_p,
17671 		       bool integral_constant_expression_p)
17672 {
17673 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
17674 #define RECUR(NODE)						\
17675   tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
17676 			 /*function_p=*/false,			\
17677 			 integral_constant_expression_p)
17678 
17679   tree retval, op1;
17680   location_t loc;
17681 
17682   if (t == NULL_TREE || t == error_mark_node)
17683     return t;
17684 
17685   loc = input_location;
17686   if (EXPR_HAS_LOCATION (t))
17687     input_location = EXPR_LOCATION (t);
17688 
17689   /* N3276 decltype magic only applies to calls at the top level or on the
17690      right side of a comma.  */
17691   tsubst_flags_t decltype_flag = (complain & tf_decltype);
17692   complain &= ~tf_decltype;
17693 
17694   switch (TREE_CODE (t))
17695     {
17696     case USING_DECL:
17697       t = DECL_NAME (t);
17698       /* Fall through.  */
17699     case IDENTIFIER_NODE:
17700       {
17701 	tree decl;
17702 	cp_id_kind idk;
17703 	bool non_integral_constant_expression_p;
17704 	const char *error_msg;
17705 
17706 	if (IDENTIFIER_CONV_OP_P (t))
17707 	  {
17708 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17709 	    t = make_conv_op_name (new_type);
17710 	  }
17711 
17712 	/* Look up the name.  */
17713 	decl = lookup_name (t);
17714 
17715 	/* By convention, expressions use ERROR_MARK_NODE to indicate
17716 	   failure, not NULL_TREE.  */
17717 	if (decl == NULL_TREE)
17718 	  decl = error_mark_node;
17719 
17720 	decl = finish_id_expression (t, decl, NULL_TREE,
17721 				     &idk,
17722 				     integral_constant_expression_p,
17723           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
17724 				     &non_integral_constant_expression_p,
17725 				     /*template_p=*/false,
17726 				     /*done=*/true,
17727 				     /*address_p=*/false,
17728 				     /*template_arg_p=*/false,
17729 				     &error_msg,
17730 				     input_location);
17731 	if (error_msg)
17732 	  error (error_msg);
17733 	if (!function_p && identifier_p (decl))
17734 	  {
17735 	    if (complain & tf_error)
17736 	      unqualified_name_lookup_error (decl);
17737 	    decl = error_mark_node;
17738 	  }
17739 	RETURN (decl);
17740       }
17741 
17742     case TEMPLATE_ID_EXPR:
17743       {
17744 	tree object;
17745 	tree templ = RECUR (TREE_OPERAND (t, 0));
17746 	tree targs = TREE_OPERAND (t, 1);
17747 
17748 	if (targs)
17749 	  targs = tsubst_template_args (targs, args, complain, in_decl);
17750 	if (targs == error_mark_node)
17751 	  RETURN (error_mark_node);
17752 
17753 	if (TREE_CODE (templ) == SCOPE_REF)
17754 	  {
17755 	    tree name = TREE_OPERAND (templ, 1);
17756 	    tree tid = lookup_template_function (name, targs);
17757 	    TREE_OPERAND (templ, 1) = tid;
17758 	    RETURN (templ);
17759 	  }
17760 
17761 	if (variable_template_p (templ))
17762 	  RETURN (lookup_and_finish_template_variable (templ, targs, complain));
17763 
17764 	if (TREE_CODE (templ) == COMPONENT_REF)
17765 	  {
17766 	    object = TREE_OPERAND (templ, 0);
17767 	    templ = TREE_OPERAND (templ, 1);
17768 	  }
17769 	else
17770 	  object = NULL_TREE;
17771 	templ = lookup_template_function (templ, targs);
17772 
17773 	if (object)
17774 	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
17775 			 object, templ, NULL_TREE));
17776 	else
17777 	  RETURN (baselink_for_fns (templ));
17778       }
17779 
17780     case INDIRECT_REF:
17781       {
17782 	tree r = RECUR (TREE_OPERAND (t, 0));
17783 
17784 	if (REFERENCE_REF_P (t))
17785 	  {
17786 	    /* A type conversion to reference type will be enclosed in
17787 	       such an indirect ref, but the substitution of the cast
17788 	       will have also added such an indirect ref.  */
17789 	    r = convert_from_reference (r);
17790 	  }
17791 	else
17792 	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
17793 				    complain|decltype_flag);
17794 
17795 	if (REF_PARENTHESIZED_P (t))
17796 	  r = force_paren_expr (r);
17797 
17798 	RETURN (r);
17799       }
17800 
17801     case NOP_EXPR:
17802       {
17803 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17804 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17805 	RETURN (build_nop (type, op0));
17806       }
17807 
17808     case IMPLICIT_CONV_EXPR:
17809       {
17810 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17811 	tree expr = RECUR (TREE_OPERAND (t, 0));
17812 	if (dependent_type_p (type) || type_dependent_expression_p (expr))
17813 	  {
17814 	    retval = copy_node (t);
17815 	    TREE_TYPE (retval) = type;
17816 	    TREE_OPERAND (retval, 0) = expr;
17817 	    RETURN (retval);
17818 	  }
17819 	if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
17820 	  /* We'll pass this to convert_nontype_argument again, we don't need
17821 	     to actually perform any conversion here.  */
17822 	  RETURN (expr);
17823 	int flags = LOOKUP_IMPLICIT;
17824 	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
17825 	  flags = LOOKUP_NORMAL;
17826 	RETURN (perform_implicit_conversion_flags (type, expr, complain,
17827 						  flags));
17828       }
17829 
17830     case CONVERT_EXPR:
17831       {
17832 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17833 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17834 	if (op0 == error_mark_node)
17835 	  RETURN (error_mark_node);
17836 	RETURN (build1 (CONVERT_EXPR, type, op0));
17837       }
17838 
17839     case CAST_EXPR:
17840     case REINTERPRET_CAST_EXPR:
17841     case CONST_CAST_EXPR:
17842     case DYNAMIC_CAST_EXPR:
17843     case STATIC_CAST_EXPR:
17844       {
17845 	tree type;
17846 	tree op, r = NULL_TREE;
17847 
17848 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17849 	if (integral_constant_expression_p
17850 	    && !cast_valid_in_integral_constant_expression_p (type))
17851 	  {
17852             if (complain & tf_error)
17853               error ("a cast to a type other than an integral or "
17854                      "enumeration type cannot appear in a constant-expression");
17855 	    RETURN (error_mark_node);
17856 	  }
17857 
17858 	op = RECUR (TREE_OPERAND (t, 0));
17859 
17860 	warning_sentinel s(warn_useless_cast);
17861 	warning_sentinel s2(warn_ignored_qualifiers);
17862 	switch (TREE_CODE (t))
17863 	  {
17864 	  case CAST_EXPR:
17865 	    r = build_functional_cast (type, op, complain);
17866 	    break;
17867 	  case REINTERPRET_CAST_EXPR:
17868 	    r = build_reinterpret_cast (type, op, complain);
17869 	    break;
17870 	  case CONST_CAST_EXPR:
17871 	    r = build_const_cast (type, op, complain);
17872 	    break;
17873 	  case DYNAMIC_CAST_EXPR:
17874 	    r = build_dynamic_cast (type, op, complain);
17875 	    break;
17876 	  case STATIC_CAST_EXPR:
17877 	    r = build_static_cast (type, op, complain);
17878 	    break;
17879 	  default:
17880 	    gcc_unreachable ();
17881 	  }
17882 
17883 	RETURN (r);
17884       }
17885 
17886     case POSTDECREMENT_EXPR:
17887     case POSTINCREMENT_EXPR:
17888       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
17889 						args, complain, in_decl);
17890       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
17891 				complain|decltype_flag));
17892 
17893     case PREDECREMENT_EXPR:
17894     case PREINCREMENT_EXPR:
17895     case NEGATE_EXPR:
17896     case BIT_NOT_EXPR:
17897     case ABS_EXPR:
17898     case TRUTH_NOT_EXPR:
17899     case UNARY_PLUS_EXPR:  /* Unary + */
17900     case REALPART_EXPR:
17901     case IMAGPART_EXPR:
17902       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
17903 				RECUR (TREE_OPERAND (t, 0)),
17904 				complain|decltype_flag));
17905 
17906     case FIX_TRUNC_EXPR:
17907       gcc_unreachable ();
17908 
17909     case ADDR_EXPR:
17910       op1 = TREE_OPERAND (t, 0);
17911       if (TREE_CODE (op1) == LABEL_DECL)
17912 	RETURN (finish_label_address_expr (DECL_NAME (op1),
17913 					  EXPR_LOCATION (op1)));
17914       if (TREE_CODE (op1) == SCOPE_REF)
17915 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
17916 				   /*done=*/true, /*address_p=*/true);
17917       else
17918 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
17919 						  in_decl);
17920       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
17921 				complain|decltype_flag));
17922 
17923     case PLUS_EXPR:
17924     case MINUS_EXPR:
17925     case MULT_EXPR:
17926     case TRUNC_DIV_EXPR:
17927     case CEIL_DIV_EXPR:
17928     case FLOOR_DIV_EXPR:
17929     case ROUND_DIV_EXPR:
17930     case EXACT_DIV_EXPR:
17931     case BIT_AND_EXPR:
17932     case BIT_IOR_EXPR:
17933     case BIT_XOR_EXPR:
17934     case TRUNC_MOD_EXPR:
17935     case FLOOR_MOD_EXPR:
17936     case TRUTH_ANDIF_EXPR:
17937     case TRUTH_ORIF_EXPR:
17938     case TRUTH_AND_EXPR:
17939     case TRUTH_OR_EXPR:
17940     case RSHIFT_EXPR:
17941     case LSHIFT_EXPR:
17942     case RROTATE_EXPR:
17943     case LROTATE_EXPR:
17944     case EQ_EXPR:
17945     case NE_EXPR:
17946     case MAX_EXPR:
17947     case MIN_EXPR:
17948     case LE_EXPR:
17949     case GE_EXPR:
17950     case LT_EXPR:
17951     case GT_EXPR:
17952     case MEMBER_REF:
17953     case DOTSTAR_EXPR:
17954       {
17955 	warning_sentinel s1(warn_type_limits);
17956 	warning_sentinel s2(warn_div_by_zero);
17957 	warning_sentinel s3(warn_logical_op);
17958 	warning_sentinel s4(warn_tautological_compare);
17959 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17960 	tree op1 = RECUR (TREE_OPERAND (t, 1));
17961 	tree r = build_x_binary_op
17962 	  (input_location, TREE_CODE (t),
17963 	   op0,
17964 	   (TREE_NO_WARNING (TREE_OPERAND (t, 0))
17965 	    ? ERROR_MARK
17966 	    : TREE_CODE (TREE_OPERAND (t, 0))),
17967 	   op1,
17968 	   (TREE_NO_WARNING (TREE_OPERAND (t, 1))
17969 	    ? ERROR_MARK
17970 	    : TREE_CODE (TREE_OPERAND (t, 1))),
17971 	   /*overload=*/NULL,
17972 	   complain|decltype_flag);
17973 	if (EXPR_P (r) && TREE_NO_WARNING (t))
17974 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
17975 
17976 	RETURN (r);
17977       }
17978 
17979     case POINTER_PLUS_EXPR:
17980       {
17981 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17982 	tree op1 = RECUR (TREE_OPERAND (t, 1));
17983 	RETURN (fold_build_pointer_plus (op0, op1));
17984       }
17985 
17986     case SCOPE_REF:
17987       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
17988 				  /*address_p=*/false));
17989     case ARRAY_REF:
17990       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
17991 						args, complain, in_decl);
17992       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
17993 				 RECUR (TREE_OPERAND (t, 1)),
17994 				 complain|decltype_flag));
17995 
17996     case SIZEOF_EXPR:
17997       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
17998 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
17999 	RETURN (tsubst_copy (t, args, complain, in_decl));
18000       /* Fall through */
18001 
18002     case ALIGNOF_EXPR:
18003       {
18004 	tree r;
18005 
18006 	op1 = TREE_OPERAND (t, 0);
18007 	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
18008 	  op1 = TREE_TYPE (op1);
18009 	bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
18010 			    && ALIGNOF_EXPR_STD_P (t));
18011         if (!args)
18012 	  {
18013 	    /* When there are no ARGS, we are trying to evaluate a
18014 	       non-dependent expression from the parser.  Trying to do
18015 	       the substitutions may not work.  */
18016 	    if (!TYPE_P (op1))
18017 	      op1 = TREE_TYPE (op1);
18018 	  }
18019 	else
18020 	  {
18021 	    ++cp_unevaluated_operand;
18022 	    ++c_inhibit_evaluation_warnings;
18023 	    if (TYPE_P (op1))
18024 	      op1 = tsubst (op1, args, complain, in_decl);
18025 	    else
18026 	      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18027 					   /*function_p=*/false,
18028 					   /*integral_constant_expression_p=*/
18029 					   false);
18030 	    --cp_unevaluated_operand;
18031 	    --c_inhibit_evaluation_warnings;
18032 	  }
18033         if (TYPE_P (op1))
18034 	  r = cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), std_alignof,
18035 					  complain & tf_error);
18036 	else
18037 	  r = cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
18038 					  complain & tf_error);
18039 	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
18040 	  {
18041 	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
18042 	      {
18043 		if (!processing_template_decl && TYPE_P (op1))
18044 		  {
18045 		    r = build_min (SIZEOF_EXPR, size_type_node,
18046 				   build1 (NOP_EXPR, op1, error_mark_node));
18047 		    SIZEOF_EXPR_TYPE_P (r) = 1;
18048 		  }
18049 		else
18050 		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
18051 		TREE_SIDE_EFFECTS (r) = 0;
18052 		TREE_READONLY (r) = 1;
18053 	      }
18054 	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
18055 	  }
18056 	RETURN (r);
18057       }
18058 
18059     case AT_ENCODE_EXPR:
18060       {
18061 	op1 = TREE_OPERAND (t, 0);
18062 	++cp_unevaluated_operand;
18063 	++c_inhibit_evaluation_warnings;
18064 	op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18065 				     /*function_p=*/false,
18066 				     /*integral_constant_expression_p=*/false);
18067 	--cp_unevaluated_operand;
18068 	--c_inhibit_evaluation_warnings;
18069 	RETURN (objc_build_encode_expr (op1));
18070       }
18071 
18072     case NOEXCEPT_EXPR:
18073       op1 = TREE_OPERAND (t, 0);
18074       ++cp_unevaluated_operand;
18075       ++c_inhibit_evaluation_warnings;
18076       ++cp_noexcept_operand;
18077       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18078 				   /*function_p=*/false,
18079 				   /*integral_constant_expression_p=*/false);
18080       --cp_unevaluated_operand;
18081       --c_inhibit_evaluation_warnings;
18082       --cp_noexcept_operand;
18083       RETURN (finish_noexcept_expr (op1, complain));
18084 
18085     case MODOP_EXPR:
18086       {
18087 	warning_sentinel s(warn_div_by_zero);
18088 	tree lhs = RECUR (TREE_OPERAND (t, 0));
18089 	tree rhs = RECUR (TREE_OPERAND (t, 2));
18090 	tree r = build_x_modify_expr
18091 	  (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
18092 	   complain|decltype_flag);
18093 	/* TREE_NO_WARNING must be set if either the expression was
18094 	   parenthesized or it uses an operator such as >>= rather
18095 	   than plain assignment.  In the former case, it was already
18096 	   set and must be copied.  In the latter case,
18097 	   build_x_modify_expr sets it and it must not be reset
18098 	   here.  */
18099 	if (TREE_NO_WARNING (t))
18100 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
18101 
18102 	RETURN (r);
18103       }
18104 
18105     case ARROW_EXPR:
18106       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18107 						args, complain, in_decl);
18108       /* Remember that there was a reference to this entity.  */
18109       if (DECL_P (op1)
18110 	  && !mark_used (op1, complain) && !(complain & tf_error))
18111 	RETURN (error_mark_node);
18112       RETURN (build_x_arrow (input_location, op1, complain));
18113 
18114     case NEW_EXPR:
18115       {
18116 	tree placement = RECUR (TREE_OPERAND (t, 0));
18117 	tree init = RECUR (TREE_OPERAND (t, 3));
18118 	vec<tree, va_gc> *placement_vec;
18119 	vec<tree, va_gc> *init_vec;
18120 	tree ret;
18121 
18122 	if (placement == NULL_TREE)
18123 	  placement_vec = NULL;
18124 	else
18125 	  {
18126 	    placement_vec = make_tree_vector ();
18127 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
18128 	      vec_safe_push (placement_vec, TREE_VALUE (placement));
18129 	  }
18130 
18131 	/* If there was an initializer in the original tree, but it
18132 	   instantiated to an empty list, then we should pass a
18133 	   non-NULL empty vector to tell build_new that it was an
18134 	   empty initializer() rather than no initializer.  This can
18135 	   only happen when the initializer is a pack expansion whose
18136 	   parameter packs are of length zero.  */
18137 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
18138 	  init_vec = NULL;
18139 	else
18140 	  {
18141 	    init_vec = make_tree_vector ();
18142 	    if (init == void_node)
18143 	      gcc_assert (init_vec != NULL);
18144 	    else
18145 	      {
18146 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
18147 		  vec_safe_push (init_vec, TREE_VALUE (init));
18148 	      }
18149 	  }
18150 
18151 	tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
18152 	tree op2 = RECUR (TREE_OPERAND (t, 2));
18153 	ret = build_new (&placement_vec, op1, op2, &init_vec,
18154 			 NEW_EXPR_USE_GLOBAL (t),
18155 			 complain);
18156 
18157 	if (placement_vec != NULL)
18158 	  release_tree_vector (placement_vec);
18159 	if (init_vec != NULL)
18160 	  release_tree_vector (init_vec);
18161 
18162 	RETURN (ret);
18163       }
18164 
18165     case DELETE_EXPR:
18166       {
18167 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18168 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18169 	RETURN (delete_sanity (op0, op1,
18170 			       DELETE_EXPR_USE_VEC (t),
18171 			       DELETE_EXPR_USE_GLOBAL (t),
18172 			       complain));
18173       }
18174 
18175     case COMPOUND_EXPR:
18176       {
18177 	tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
18178 					  complain & ~tf_decltype, in_decl,
18179 					  /*function_p=*/false,
18180 					  integral_constant_expression_p);
18181 	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
18182 				       op0,
18183 				       RECUR (TREE_OPERAND (t, 1)),
18184 				       complain|decltype_flag));
18185       }
18186 
18187     case CALL_EXPR:
18188       {
18189 	tree function;
18190 	vec<tree, va_gc> *call_args;
18191 	unsigned int nargs, i;
18192 	bool qualified_p;
18193 	bool koenig_p;
18194 	tree ret;
18195 
18196 	function = CALL_EXPR_FN (t);
18197 	/* Internal function with no arguments.  */
18198 	if (function == NULL_TREE && call_expr_nargs (t) == 0)
18199 	  RETURN (t);
18200 
18201 	/* When we parsed the expression, we determined whether or
18202 	   not Koenig lookup should be performed.  */
18203 	koenig_p = KOENIG_LOOKUP_P (t);
18204 	if (function == NULL_TREE)
18205 	  {
18206 	    koenig_p = false;
18207 	    qualified_p = false;
18208 	  }
18209 	else if (TREE_CODE (function) == SCOPE_REF)
18210 	  {
18211 	    qualified_p = true;
18212 	    function = tsubst_qualified_id (function, args, complain, in_decl,
18213 					    /*done=*/false,
18214 					    /*address_p=*/false);
18215 	  }
18216 	else if (koenig_p && identifier_p (function))
18217 	  {
18218 	    /* Do nothing; calling tsubst_copy_and_build on an identifier
18219 	       would incorrectly perform unqualified lookup again.
18220 
18221 	       Note that we can also have an IDENTIFIER_NODE if the earlier
18222 	       unqualified lookup found a member function; in that case
18223 	       koenig_p will be false and we do want to do the lookup
18224 	       again to find the instantiated member function.
18225 
18226 	       FIXME but doing that causes c++/15272, so we need to stop
18227 	       using IDENTIFIER_NODE in that situation.  */
18228 	    qualified_p = false;
18229 	  }
18230 	else
18231 	  {
18232 	    if (TREE_CODE (function) == COMPONENT_REF)
18233 	      {
18234 		tree op = TREE_OPERAND (function, 1);
18235 
18236 		qualified_p = (TREE_CODE (op) == SCOPE_REF
18237 			       || (BASELINK_P (op)
18238 				   && BASELINK_QUALIFIED_P (op)));
18239 	      }
18240 	    else
18241 	      qualified_p = false;
18242 
18243 	    if (TREE_CODE (function) == ADDR_EXPR
18244 		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
18245 	      /* Avoid error about taking the address of a constructor.  */
18246 	      function = TREE_OPERAND (function, 0);
18247 
18248 	    function = tsubst_copy_and_build (function, args, complain,
18249 					      in_decl,
18250 					      !qualified_p,
18251 					      integral_constant_expression_p);
18252 
18253 	    if (BASELINK_P (function))
18254 	      qualified_p = true;
18255 	  }
18256 
18257 	nargs = call_expr_nargs (t);
18258 	call_args = make_tree_vector ();
18259 	for (i = 0; i < nargs; ++i)
18260 	  {
18261 	    tree arg = CALL_EXPR_ARG (t, i);
18262 
18263 	    if (!PACK_EXPANSION_P (arg))
18264 	      vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
18265 	    else
18266 	      {
18267 		/* Expand the pack expansion and push each entry onto
18268 		   CALL_ARGS.  */
18269 		arg = tsubst_pack_expansion (arg, args, complain, in_decl);
18270 		if (TREE_CODE (arg) == TREE_VEC)
18271 		  {
18272 		    unsigned int len, j;
18273 
18274 		    len = TREE_VEC_LENGTH (arg);
18275 		    for (j = 0; j < len; ++j)
18276 		      {
18277 			tree value = TREE_VEC_ELT (arg, j);
18278 			if (value != NULL_TREE)
18279 			  value = convert_from_reference (value);
18280 			vec_safe_push (call_args, value);
18281 		      }
18282 		  }
18283 		else
18284 		  {
18285 		    /* A partial substitution.  Add one entry.  */
18286 		    vec_safe_push (call_args, arg);
18287 		  }
18288 	      }
18289 	  }
18290 
18291 	/* We do not perform argument-dependent lookup if normal
18292 	   lookup finds a non-function, in accordance with the
18293 	   expected resolution of DR 218.  */
18294 	if (koenig_p
18295 	    && ((is_overloaded_fn (function)
18296 		 /* If lookup found a member function, the Koenig lookup is
18297 		    not appropriate, even if an unqualified-name was used
18298 		    to denote the function.  */
18299 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
18300 		|| identifier_p (function))
18301 	    /* Only do this when substitution turns a dependent call
18302 	       into a non-dependent call.  */
18303 	    && type_dependent_expression_p_push (t)
18304 	    && !any_type_dependent_arguments_p (call_args))
18305 	  function = perform_koenig_lookup (function, call_args, tf_none);
18306 
18307 	if (function != NULL_TREE
18308 	    && identifier_p (function)
18309 	    && !any_type_dependent_arguments_p (call_args))
18310 	  {
18311 	    if (koenig_p && (complain & tf_warning_or_error))
18312 	      {
18313 		/* For backwards compatibility and good diagnostics, try
18314 		   the unqualified lookup again if we aren't in SFINAE
18315 		   context.  */
18316 		tree unq = (tsubst_copy_and_build
18317 			    (function, args, complain, in_decl, true,
18318 			     integral_constant_expression_p));
18319 		if (unq == error_mark_node)
18320 		  {
18321 		    release_tree_vector (call_args);
18322 		    RETURN (error_mark_node);
18323 		  }
18324 
18325 		if (unq != function)
18326 		  {
18327 		    /* In a lambda fn, we have to be careful to not
18328 		       introduce new this captures.  Legacy code can't
18329 		       be using lambdas anyway, so it's ok to be
18330 		       stricter.  */
18331 		    bool in_lambda = (current_class_type
18332 				      && LAMBDA_TYPE_P (current_class_type));
18333 		    char const *const msg
18334 		      = G_("%qD was not declared in this scope, "
18335 			   "and no declarations were found by "
18336 			   "argument-dependent lookup at the point "
18337 			   "of instantiation");
18338 
18339 		    bool diag = true;
18340 		    if (in_lambda)
18341 		      error_at (EXPR_LOC_OR_LOC (t, input_location),
18342 				msg, function);
18343 		    else
18344 		      diag = permerror (EXPR_LOC_OR_LOC (t, input_location),
18345 					msg, function);
18346 		    if (diag)
18347 		      {
18348 			tree fn = unq;
18349 
18350 			if (INDIRECT_REF_P (fn))
18351 			  fn = TREE_OPERAND (fn, 0);
18352 			if (is_overloaded_fn (fn))
18353 			  fn = get_first_fn (fn);
18354 
18355 			if (!DECL_P (fn))
18356 			  /* Can't say anything more.  */;
18357 			else if (DECL_CLASS_SCOPE_P (fn))
18358 			  {
18359 			    location_t loc = EXPR_LOC_OR_LOC (t,
18360 							      input_location);
18361 			    inform (loc,
18362 				    "declarations in dependent base %qT are "
18363 				    "not found by unqualified lookup",
18364 				    DECL_CLASS_CONTEXT (fn));
18365 			    if (current_class_ptr)
18366 			      inform (loc,
18367 				      "use %<this->%D%> instead", function);
18368 			    else
18369 			      inform (loc,
18370 				      "use %<%T::%D%> instead",
18371 				      current_class_name, function);
18372 			  }
18373 			else
18374 			  inform (DECL_SOURCE_LOCATION (fn),
18375 				  "%qD declared here, later in the "
18376 				  "translation unit", fn);
18377 			if (in_lambda)
18378 			  {
18379 			    release_tree_vector (call_args);
18380 			    RETURN (error_mark_node);
18381 			  }
18382 		      }
18383 
18384 		    function = unq;
18385 		  }
18386 	      }
18387 	    if (identifier_p (function))
18388 	      {
18389 		if (complain & tf_error)
18390 		  unqualified_name_lookup_error (function);
18391 		release_tree_vector (call_args);
18392 		RETURN (error_mark_node);
18393 	      }
18394 	  }
18395 
18396 	/* Remember that there was a reference to this entity.  */
18397 	if (function != NULL_TREE
18398 	    && DECL_P (function)
18399 	    && !mark_used (function, complain) && !(complain & tf_error))
18400 	  {
18401 	    release_tree_vector (call_args);
18402 	    RETURN (error_mark_node);
18403 	  }
18404 
18405 	/* Put back tf_decltype for the actual call.  */
18406 	complain |= decltype_flag;
18407 
18408 	if (function == NULL_TREE)
18409 	  switch (CALL_EXPR_IFN (t))
18410 	    {
18411 	    case IFN_LAUNDER:
18412 	      gcc_assert (nargs == 1);
18413 	      if (vec_safe_length (call_args) != 1)
18414 		{
18415 		  error_at (EXPR_LOC_OR_LOC (t, input_location),
18416 			    "wrong number of arguments to "
18417 			    "%<__builtin_launder%>");
18418 		  ret = error_mark_node;
18419 		}
18420 	      else
18421 		ret = finish_builtin_launder (EXPR_LOC_OR_LOC (t,
18422 							       input_location),
18423 					      (*call_args)[0], complain);
18424 	      break;
18425 
18426 	    default:
18427 	      /* Unsupported internal function with arguments.  */
18428 	      gcc_unreachable ();
18429 	    }
18430 	else if (TREE_CODE (function) == OFFSET_REF)
18431 	  ret = build_offset_ref_call_from_tree (function, &call_args,
18432 						 complain);
18433 	else if (TREE_CODE (function) == COMPONENT_REF)
18434 	  {
18435 	    tree instance = TREE_OPERAND (function, 0);
18436 	    tree fn = TREE_OPERAND (function, 1);
18437 
18438 	    if (processing_template_decl
18439 		&& (type_dependent_expression_p (instance)
18440 		    || (!BASELINK_P (fn)
18441 			&& TREE_CODE (fn) != FIELD_DECL)
18442 		    || type_dependent_expression_p (fn)
18443 		    || any_type_dependent_arguments_p (call_args)))
18444 	      ret = build_min_nt_call_vec (function, call_args);
18445 	    else if (!BASELINK_P (fn))
18446 	      ret = finish_call_expr (function, &call_args,
18447 				       /*disallow_virtual=*/false,
18448 				       /*koenig_p=*/false,
18449 				       complain);
18450 	    else
18451 	      ret = (build_new_method_call
18452 		      (instance, fn,
18453 		       &call_args, NULL_TREE,
18454 		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
18455 		       /*fn_p=*/NULL,
18456 		       complain));
18457 	  }
18458 	else
18459 	  ret = finish_call_expr (function, &call_args,
18460 				  /*disallow_virtual=*/qualified_p,
18461 				  koenig_p,
18462 				  complain);
18463 
18464 	release_tree_vector (call_args);
18465 
18466 	if (ret != error_mark_node)
18467 	  {
18468 	    bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
18469 	    bool ord = CALL_EXPR_ORDERED_ARGS (t);
18470 	    bool rev = CALL_EXPR_REVERSE_ARGS (t);
18471 	    bool thk = CALL_FROM_THUNK_P (t);
18472 	    if (op || ord || rev || thk)
18473 	      {
18474 		function = extract_call_expr (ret);
18475 		CALL_EXPR_OPERATOR_SYNTAX (function) = op;
18476 		CALL_EXPR_ORDERED_ARGS (function) = ord;
18477 		CALL_EXPR_REVERSE_ARGS (function) = rev;
18478 		if (thk)
18479 		  {
18480 		    if (TREE_CODE (function) == CALL_EXPR)
18481 		      CALL_FROM_THUNK_P (function) = true;
18482 		    else
18483 		      AGGR_INIT_FROM_THUNK_P (function) = true;
18484 		    /* The thunk location is not interesting.  */
18485 		    SET_EXPR_LOCATION (function, UNKNOWN_LOCATION);
18486 		  }
18487 	      }
18488 	  }
18489 
18490 	RETURN (ret);
18491       }
18492 
18493     case COND_EXPR:
18494       {
18495 	tree cond = RECUR (TREE_OPERAND (t, 0));
18496 	tree folded_cond = fold_non_dependent_expr (cond);
18497 	tree exp1, exp2;
18498 
18499 	if (TREE_CODE (folded_cond) == INTEGER_CST)
18500 	  {
18501 	    if (integer_zerop (folded_cond))
18502 	      {
18503 		++c_inhibit_evaluation_warnings;
18504 		exp1 = RECUR (TREE_OPERAND (t, 1));
18505 		--c_inhibit_evaluation_warnings;
18506 		exp2 = RECUR (TREE_OPERAND (t, 2));
18507 	      }
18508 	    else
18509 	      {
18510 		exp1 = RECUR (TREE_OPERAND (t, 1));
18511 		++c_inhibit_evaluation_warnings;
18512 		exp2 = RECUR (TREE_OPERAND (t, 2));
18513 		--c_inhibit_evaluation_warnings;
18514 	      }
18515 	    cond = folded_cond;
18516 	  }
18517 	else
18518 	  {
18519 	    exp1 = RECUR (TREE_OPERAND (t, 1));
18520 	    exp2 = RECUR (TREE_OPERAND (t, 2));
18521 	  }
18522 
18523 	warning_sentinel s(warn_duplicated_branches);
18524 	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
18525 					 cond, exp1, exp2, complain));
18526       }
18527 
18528     case PSEUDO_DTOR_EXPR:
18529       {
18530 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18531 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18532 	tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
18533 	RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
18534 					       input_location));
18535       }
18536 
18537     case TREE_LIST:
18538       {
18539 	tree purpose, value, chain;
18540 
18541 	if (t == void_list_node)
18542 	  RETURN (t);
18543 
18544         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
18545             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
18546           {
18547             /* We have pack expansions, so expand those and
18548                create a new list out of it.  */
18549             tree purposevec = NULL_TREE;
18550             tree valuevec = NULL_TREE;
18551             tree chain;
18552             int i, len = -1;
18553 
18554             /* Expand the argument expressions.  */
18555             if (TREE_PURPOSE (t))
18556               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
18557                                                  complain, in_decl);
18558             if (TREE_VALUE (t))
18559               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
18560                                                complain, in_decl);
18561 
18562             /* Build the rest of the list.  */
18563             chain = TREE_CHAIN (t);
18564             if (chain && chain != void_type_node)
18565               chain = RECUR (chain);
18566 
18567             /* Determine the number of arguments.  */
18568             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
18569               {
18570                 len = TREE_VEC_LENGTH (purposevec);
18571                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
18572               }
18573             else if (TREE_CODE (valuevec) == TREE_VEC)
18574               len = TREE_VEC_LENGTH (valuevec);
18575             else
18576               {
18577                 /* Since we only performed a partial substitution into
18578                    the argument pack, we only RETURN (a single list
18579                    node.  */
18580                 if (purposevec == TREE_PURPOSE (t)
18581                     && valuevec == TREE_VALUE (t)
18582                     && chain == TREE_CHAIN (t))
18583                   RETURN (t);
18584 
18585                 RETURN (tree_cons (purposevec, valuevec, chain));
18586               }
18587 
18588             /* Convert the argument vectors into a TREE_LIST */
18589             i = len;
18590             while (i > 0)
18591               {
18592                 /* Grab the Ith values.  */
18593                 i--;
18594                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
18595 		                     : NULL_TREE;
18596                 value
18597 		  = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
18598                              : NULL_TREE;
18599 
18600                 /* Build the list (backwards).  */
18601                 chain = tree_cons (purpose, value, chain);
18602               }
18603 
18604             RETURN (chain);
18605           }
18606 
18607 	purpose = TREE_PURPOSE (t);
18608 	if (purpose)
18609 	  purpose = RECUR (purpose);
18610 	value = TREE_VALUE (t);
18611 	if (value)
18612 	  value = RECUR (value);
18613 	chain = TREE_CHAIN (t);
18614 	if (chain && chain != void_type_node)
18615 	  chain = RECUR (chain);
18616 	if (purpose == TREE_PURPOSE (t)
18617 	    && value == TREE_VALUE (t)
18618 	    && chain == TREE_CHAIN (t))
18619 	  RETURN (t);
18620 	RETURN (tree_cons (purpose, value, chain));
18621       }
18622 
18623     case COMPONENT_REF:
18624       {
18625 	tree object;
18626 	tree object_type;
18627 	tree member;
18628 	tree r;
18629 
18630 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18631 						     args, complain, in_decl);
18632 	/* Remember that there was a reference to this entity.  */
18633 	if (DECL_P (object)
18634 	    && !mark_used (object, complain) && !(complain & tf_error))
18635 	  RETURN (error_mark_node);
18636 	object_type = TREE_TYPE (object);
18637 
18638 	member = TREE_OPERAND (t, 1);
18639 	if (BASELINK_P (member))
18640 	  member = tsubst_baselink (member,
18641 				    non_reference (TREE_TYPE (object)),
18642 				    args, complain, in_decl);
18643 	else
18644 	  member = tsubst_copy (member, args, complain, in_decl);
18645 	if (member == error_mark_node)
18646 	  RETURN (error_mark_node);
18647 
18648 	if (TREE_CODE (member) == FIELD_DECL)
18649 	  {
18650 	    r = finish_non_static_data_member (member, object, NULL_TREE);
18651 	    if (TREE_CODE (r) == COMPONENT_REF)
18652 	      REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
18653 	    RETURN (r);
18654 	  }
18655 	else if (type_dependent_expression_p (object))
18656 	  /* We can't do much here.  */;
18657 	else if (!CLASS_TYPE_P (object_type))
18658 	  {
18659 	    if (scalarish_type_p (object_type))
18660 	      {
18661 		tree s = NULL_TREE;
18662 		tree dtor = member;
18663 
18664 		if (TREE_CODE (dtor) == SCOPE_REF)
18665 		  {
18666 		    s = TREE_OPERAND (dtor, 0);
18667 		    dtor = TREE_OPERAND (dtor, 1);
18668 		  }
18669 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
18670 		  {
18671 		    dtor = TREE_OPERAND (dtor, 0);
18672 		    if (TYPE_P (dtor))
18673 		      RETURN (finish_pseudo_destructor_expr
18674 			      (object, s, dtor, input_location));
18675 		  }
18676 	      }
18677 	  }
18678 	else if (TREE_CODE (member) == SCOPE_REF
18679 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
18680 	  {
18681 	    /* Lookup the template functions now that we know what the
18682 	       scope is.  */
18683 	    tree scope = TREE_OPERAND (member, 0);
18684 	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
18685 	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
18686 	    member = lookup_qualified_name (scope, tmpl,
18687 					    /*is_type_p=*/false,
18688 					    /*complain=*/false);
18689 	    if (BASELINK_P (member))
18690 	      {
18691 		BASELINK_FUNCTIONS (member)
18692 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
18693 			      args);
18694 		member = (adjust_result_of_qualified_name_lookup
18695 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
18696 			   object_type));
18697 	      }
18698 	    else
18699 	      {
18700 		qualified_name_lookup_error (scope, tmpl, member,
18701 					     input_location);
18702 		RETURN (error_mark_node);
18703 	      }
18704 	  }
18705 	else if (TREE_CODE (member) == SCOPE_REF
18706 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
18707 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
18708 	  {
18709 	    if (complain & tf_error)
18710 	      {
18711 		if (TYPE_P (TREE_OPERAND (member, 0)))
18712 		  error ("%qT is not a class or namespace",
18713 			 TREE_OPERAND (member, 0));
18714 		else
18715 		  error ("%qD is not a class or namespace",
18716 			 TREE_OPERAND (member, 0));
18717 	      }
18718 	    RETURN (error_mark_node);
18719 	  }
18720 
18721 	r = finish_class_member_access_expr (object, member,
18722 					     /*template_p=*/false,
18723 					     complain);
18724 	if (TREE_CODE (r) == COMPONENT_REF)
18725 	  REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
18726 	RETURN (r);
18727       }
18728 
18729     case THROW_EXPR:
18730       RETURN (build_throw
18731 	(RECUR (TREE_OPERAND (t, 0))));
18732 
18733     case CONSTRUCTOR:
18734       {
18735 	vec<constructor_elt, va_gc> *n;
18736 	constructor_elt *ce;
18737 	unsigned HOST_WIDE_INT idx;
18738 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18739 	bool process_index_p;
18740         int newlen;
18741         bool need_copy_p = false;
18742 	tree r;
18743 
18744 	if (type == error_mark_node)
18745 	  RETURN (error_mark_node);
18746 
18747 	/* We do not want to process the index of aggregate
18748 	   initializers as they are identifier nodes which will be
18749 	   looked up by digest_init.  */
18750 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
18751 
18752 	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
18753         newlen = vec_safe_length (n);
18754 	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
18755 	  {
18756 	    if (ce->index && process_index_p
18757 		/* An identifier index is looked up in the type
18758 		   being initialized, not the current scope.  */
18759 		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
18760 	      ce->index = RECUR (ce->index);
18761 
18762             if (PACK_EXPANSION_P (ce->value))
18763               {
18764                 /* Substitute into the pack expansion.  */
18765                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
18766                                                   in_decl);
18767 
18768 		if (ce->value == error_mark_node
18769 		    || PACK_EXPANSION_P (ce->value))
18770 		  ;
18771 		else if (TREE_VEC_LENGTH (ce->value) == 1)
18772                   /* Just move the argument into place.  */
18773                   ce->value = TREE_VEC_ELT (ce->value, 0);
18774                 else
18775                   {
18776                     /* Update the length of the final CONSTRUCTOR
18777                        arguments vector, and note that we will need to
18778                        copy.*/
18779                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
18780                     need_copy_p = true;
18781                   }
18782               }
18783             else
18784               ce->value = RECUR (ce->value);
18785 	  }
18786 
18787         if (need_copy_p)
18788           {
18789             vec<constructor_elt, va_gc> *old_n = n;
18790 
18791             vec_alloc (n, newlen);
18792             FOR_EACH_VEC_ELT (*old_n, idx, ce)
18793               {
18794                 if (TREE_CODE (ce->value) == TREE_VEC)
18795                   {
18796                     int i, len = TREE_VEC_LENGTH (ce->value);
18797                     for (i = 0; i < len; ++i)
18798                       CONSTRUCTOR_APPEND_ELT (n, 0,
18799                                               TREE_VEC_ELT (ce->value, i));
18800                   }
18801                 else
18802                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
18803               }
18804           }
18805 
18806 	r = build_constructor (init_list_type_node, n);
18807 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
18808 
18809 	if (TREE_HAS_CONSTRUCTOR (t))
18810 	  {
18811 	    fcl_t cl = fcl_functional;
18812 	    if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
18813 	      cl = fcl_c99;
18814 	    RETURN (finish_compound_literal (type, r, complain, cl));
18815 	  }
18816 
18817 	TREE_TYPE (r) = type;
18818 	RETURN (r);
18819       }
18820 
18821     case TYPEID_EXPR:
18822       {
18823 	tree operand_0 = TREE_OPERAND (t, 0);
18824 	if (TYPE_P (operand_0))
18825 	  {
18826 	    operand_0 = tsubst (operand_0, args, complain, in_decl);
18827 	    RETURN (get_typeid (operand_0, complain));
18828 	  }
18829 	else
18830 	  {
18831 	    operand_0 = RECUR (operand_0);
18832 	    RETURN (build_typeid (operand_0, complain));
18833 	  }
18834       }
18835 
18836     case VAR_DECL:
18837       if (!args)
18838 	RETURN (t);
18839       /* Fall through */
18840 
18841     case PARM_DECL:
18842       {
18843 	tree r = tsubst_copy (t, args, complain, in_decl);
18844 	/* ??? We're doing a subset of finish_id_expression here.  */
18845 	if (VAR_P (r)
18846 	    && !processing_template_decl
18847 	    && !cp_unevaluated_operand
18848 	    && (TREE_STATIC (r) || DECL_EXTERNAL (r))
18849 	    && CP_DECL_THREAD_LOCAL_P (r))
18850 	  {
18851 	    if (tree wrap = get_tls_wrapper_fn (r))
18852 	      /* Replace an evaluated use of the thread_local variable with
18853 		 a call to its wrapper.  */
18854 	      r = build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
18855 	  }
18856 	else if (outer_automatic_var_p (r))
18857 	  r = process_outer_var_ref (r, complain);
18858 
18859 	if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
18860 	  /* If the original type was a reference, we'll be wrapped in
18861 	     the appropriate INDIRECT_REF.  */
18862 	  r = convert_from_reference (r);
18863 	RETURN (r);
18864       }
18865 
18866     case VA_ARG_EXPR:
18867       {
18868 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18869 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18870 	RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
18871       }
18872 
18873     case OFFSETOF_EXPR:
18874       {
18875 	tree object_ptr
18876 	  = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
18877 				   in_decl, /*function_p=*/false,
18878 				   /*integral_constant_expression_p=*/false);
18879 	RETURN (finish_offsetof (object_ptr,
18880 				 RECUR (TREE_OPERAND (t, 0)),
18881 				 EXPR_LOCATION (t)));
18882       }
18883 
18884     case ADDRESSOF_EXPR:
18885       RETURN (cp_build_addressof (EXPR_LOCATION (t),
18886 				  RECUR (TREE_OPERAND (t, 0)), complain));
18887 
18888     case TRAIT_EXPR:
18889       {
18890 	tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
18891 			     complain, in_decl);
18892 
18893 	tree type2 = TRAIT_EXPR_TYPE2 (t);
18894 	if (type2 && TREE_CODE (type2) == TREE_LIST)
18895 	  type2 = RECUR (type2);
18896 	else if (type2)
18897 	  type2 = tsubst (type2, args, complain, in_decl);
18898 
18899 	RETURN (finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2));
18900       }
18901 
18902     case STMT_EXPR:
18903       {
18904 	tree old_stmt_expr = cur_stmt_expr;
18905 	tree stmt_expr = begin_stmt_expr ();
18906 
18907 	cur_stmt_expr = stmt_expr;
18908 	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
18909 		     integral_constant_expression_p);
18910 	stmt_expr = finish_stmt_expr (stmt_expr, false);
18911 	cur_stmt_expr = old_stmt_expr;
18912 
18913 	/* If the resulting list of expression statement is empty,
18914 	   fold it further into void_node.  */
18915 	if (empty_expr_stmt_p (stmt_expr))
18916 	  stmt_expr = void_node;
18917 
18918 	RETURN (stmt_expr);
18919       }
18920 
18921     case LAMBDA_EXPR:
18922       {
18923 	tree r = tsubst_lambda_expr (t, args, complain, in_decl);
18924 
18925 	RETURN (build_lambda_object (r));
18926       }
18927 
18928     case TARGET_EXPR:
18929       /* We can get here for a constant initializer of non-dependent type.
18930          FIXME stop folding in cp_parser_initializer_clause.  */
18931       {
18932 	tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
18933 					 complain);
18934 	RETURN (r);
18935       }
18936 
18937     case TRANSACTION_EXPR:
18938       RETURN (tsubst_expr(t, args, complain, in_decl,
18939 	     integral_constant_expression_p));
18940 
18941     case PAREN_EXPR:
18942       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
18943 
18944     case VEC_PERM_EXPR:
18945       {
18946 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18947 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18948 	tree op2 = RECUR (TREE_OPERAND (t, 2));
18949 	RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
18950 				       complain));
18951       }
18952 
18953     case REQUIRES_EXPR:
18954       RETURN (tsubst_requires_expr (t, args, complain, in_decl));
18955 
18956     case NON_LVALUE_EXPR:
18957     case VIEW_CONVERT_EXPR:
18958       /* We should only see these for location wrapper nodes, or within
18959 	 instantiate_non_dependent_expr (when args is NULL_TREE).  */
18960       gcc_assert (location_wrapper_p (t) || args == NULL_TREE);
18961       if (location_wrapper_p (t))
18962 	RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
18963 					  EXPR_LOCATION (t)));
18964       /* fallthrough.  */
18965 
18966     default:
18967       /* Handle Objective-C++ constructs, if appropriate.  */
18968       {
18969 	tree subst
18970 	  = objcp_tsubst_copy_and_build (t, args, complain,
18971 					 in_decl, /*function_p=*/false);
18972 	if (subst)
18973 	  RETURN (subst);
18974       }
18975       RETURN (tsubst_copy (t, args, complain, in_decl));
18976     }
18977 
18978 #undef RECUR
18979 #undef RETURN
18980  out:
18981   input_location = loc;
18982   return retval;
18983 }
18984 
18985 /* Verify that the instantiated ARGS are valid. For type arguments,
18986    make sure that the type's linkage is ok. For non-type arguments,
18987    make sure they are constants if they are integral or enumerations.
18988    Emit an error under control of COMPLAIN, and return TRUE on error.  */
18989 
18990 static bool
18991 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
18992 {
18993   if (dependent_template_arg_p (t))
18994     return false;
18995   if (ARGUMENT_PACK_P (t))
18996     {
18997       tree vec = ARGUMENT_PACK_ARGS (t);
18998       int len = TREE_VEC_LENGTH (vec);
18999       bool result = false;
19000       int i;
19001 
19002       for (i = 0; i < len; ++i)
19003 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
19004 	  result = true;
19005       return result;
19006     }
19007   else if (TYPE_P (t))
19008     {
19009       /* [basic.link]: A name with no linkage (notably, the name
19010 	 of a class or enumeration declared in a local scope)
19011 	 shall not be used to declare an entity with linkage.
19012 	 This implies that names with no linkage cannot be used as
19013 	 template arguments
19014 
19015 	 DR 757 relaxes this restriction for C++0x.  */
19016       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
19017 		 : no_linkage_check (t, /*relaxed_p=*/false));
19018 
19019       if (nt)
19020 	{
19021 	  /* DR 488 makes use of a type with no linkage cause
19022 	     type deduction to fail.  */
19023 	  if (complain & tf_error)
19024 	    {
19025 	      if (TYPE_UNNAMED_P (nt))
19026 		error ("%qT is/uses unnamed type", t);
19027 	      else
19028 		error ("template argument for %qD uses local type %qT",
19029 		       tmpl, t);
19030 	    }
19031 	  return true;
19032 	}
19033       /* In order to avoid all sorts of complications, we do not
19034 	 allow variably-modified types as template arguments.  */
19035       else if (variably_modified_type_p (t, NULL_TREE))
19036 	{
19037 	  if (complain & tf_error)
19038 	    error ("%qT is a variably modified type", t);
19039 	  return true;
19040 	}
19041     }
19042   /* Class template and alias template arguments should be OK.  */
19043   else if (DECL_TYPE_TEMPLATE_P (t))
19044     ;
19045   /* A non-type argument of integral or enumerated type must be a
19046      constant.  */
19047   else if (TREE_TYPE (t)
19048 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
19049 	   && !REFERENCE_REF_P (t)
19050 	   && !TREE_CONSTANT (t))
19051     {
19052       if (complain & tf_error)
19053 	error ("integral expression %qE is not constant", t);
19054       return true;
19055     }
19056   return false;
19057 }
19058 
19059 static bool
19060 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
19061 {
19062   int ix, len = DECL_NTPARMS (tmpl);
19063   bool result = false;
19064 
19065   for (ix = 0; ix != len; ix++)
19066     {
19067       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
19068 	result = true;
19069     }
19070   if (result && (complain & tf_error))
19071     error ("  trying to instantiate %qD", tmpl);
19072   return result;
19073 }
19074 
19075 /* We're out of SFINAE context now, so generate diagnostics for the access
19076    errors we saw earlier when instantiating D from TMPL and ARGS.  */
19077 
19078 static void
19079 recheck_decl_substitution (tree d, tree tmpl, tree args)
19080 {
19081   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
19082   tree type = TREE_TYPE (pattern);
19083   location_t loc = input_location;
19084 
19085   push_access_scope (d);
19086   push_deferring_access_checks (dk_no_deferred);
19087   input_location = DECL_SOURCE_LOCATION (pattern);
19088   tsubst (type, args, tf_warning_or_error, d);
19089   input_location = loc;
19090   pop_deferring_access_checks ();
19091   pop_access_scope (d);
19092 }
19093 
19094 /* Instantiate the indicated variable, function, or alias template TMPL with
19095    the template arguments in TARG_PTR.  */
19096 
19097 static tree
19098 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
19099 {
19100   tree targ_ptr = orig_args;
19101   tree fndecl;
19102   tree gen_tmpl;
19103   tree spec;
19104   bool access_ok = true;
19105 
19106   if (tmpl == error_mark_node)
19107     return error_mark_node;
19108 
19109   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
19110 
19111   /* If this function is a clone, handle it specially.  */
19112   if (DECL_CLONED_FUNCTION_P (tmpl))
19113     {
19114       tree spec;
19115       tree clone;
19116 
19117       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
19118 	 DECL_CLONED_FUNCTION.  */
19119       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
19120 				   targ_ptr, complain);
19121       if (spec == error_mark_node)
19122 	return error_mark_node;
19123 
19124       /* Look for the clone.  */
19125       FOR_EACH_CLONE (clone, spec)
19126 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
19127 	  return clone;
19128       /* We should always have found the clone by now.  */
19129       gcc_unreachable ();
19130       return NULL_TREE;
19131     }
19132 
19133   if (targ_ptr == error_mark_node)
19134     return error_mark_node;
19135 
19136   /* Check to see if we already have this specialization.  */
19137   gen_tmpl = most_general_template (tmpl);
19138   if (TMPL_ARGS_DEPTH (targ_ptr)
19139       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
19140     /* targ_ptr only has the innermost template args, so add the outer ones
19141        from tmpl, which could be either a partial instantiation or gen_tmpl (in
19142        the case of a non-dependent call within a template definition).  */
19143     targ_ptr = (add_outermost_template_args
19144 		(DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
19145 		 targ_ptr));
19146 
19147   /* It would be nice to avoid hashing here and then again in tsubst_decl,
19148      but it doesn't seem to be on the hot path.  */
19149   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
19150 
19151   gcc_assert (tmpl == gen_tmpl
19152 	      || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
19153 		  == spec)
19154 	      || fndecl == NULL_TREE);
19155 
19156   if (spec != NULL_TREE)
19157     {
19158       if (FNDECL_HAS_ACCESS_ERRORS (spec))
19159 	{
19160 	  if (complain & tf_error)
19161 	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
19162 	  return error_mark_node;
19163 	}
19164       return spec;
19165     }
19166 
19167   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
19168 			       complain))
19169     return error_mark_node;
19170 
19171   /* We are building a FUNCTION_DECL, during which the access of its
19172      parameters and return types have to be checked.  However this
19173      FUNCTION_DECL which is the desired context for access checking
19174      is not built yet.  We solve this chicken-and-egg problem by
19175      deferring all checks until we have the FUNCTION_DECL.  */
19176   push_deferring_access_checks (dk_deferred);
19177 
19178   /* Instantiation of the function happens in the context of the function
19179      template, not the context of the overload resolution we're doing.  */
19180   push_to_top_level ();
19181   /* If there are dependent arguments, e.g. because we're doing partial
19182      ordering, make sure processing_template_decl stays set.  */
19183   if (uses_template_parms (targ_ptr))
19184     ++processing_template_decl;
19185   if (DECL_CLASS_SCOPE_P (gen_tmpl))
19186     {
19187       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
19188 				   complain, gen_tmpl, true);
19189       push_nested_class (ctx);
19190     }
19191 
19192   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
19193 
19194   fndecl = NULL_TREE;
19195   if (VAR_P (pattern))
19196     {
19197       /* We need to determine if we're using a partial or explicit
19198 	 specialization now, because the type of the variable could be
19199 	 different.  */
19200       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
19201       tree elt = most_specialized_partial_spec (tid, complain);
19202       if (elt == error_mark_node)
19203 	pattern = error_mark_node;
19204       else if (elt)
19205 	{
19206 	  tree partial_tmpl = TREE_VALUE (elt);
19207 	  tree partial_args = TREE_PURPOSE (elt);
19208 	  tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
19209 	  fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
19210 	}
19211     }
19212 
19213   /* Substitute template parameters to obtain the specialization.  */
19214   if (fndecl == NULL_TREE)
19215     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
19216   if (DECL_CLASS_SCOPE_P (gen_tmpl))
19217     pop_nested_class ();
19218   pop_from_top_level ();
19219 
19220   if (fndecl == error_mark_node)
19221     {
19222       pop_deferring_access_checks ();
19223       return error_mark_node;
19224     }
19225 
19226   /* The DECL_TI_TEMPLATE should always be the immediate parent
19227      template, not the most general template.  */
19228   DECL_TI_TEMPLATE (fndecl) = tmpl;
19229   DECL_TI_ARGS (fndecl) = targ_ptr;
19230 
19231   /* Now we know the specialization, compute access previously
19232      deferred.  Do no access control for inheriting constructors,
19233      as we already checked access for the inherited constructor.  */
19234   if (!(flag_new_inheriting_ctors
19235 	&& DECL_INHERITED_CTOR (fndecl)))
19236     {
19237       push_access_scope (fndecl);
19238       if (!perform_deferred_access_checks (complain))
19239 	access_ok = false;
19240       pop_access_scope (fndecl);
19241     }
19242   pop_deferring_access_checks ();
19243 
19244   /* If we've just instantiated the main entry point for a function,
19245      instantiate all the alternate entry points as well.  We do this
19246      by cloning the instantiation of the main entry point, not by
19247      instantiating the template clones.  */
19248   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
19249     clone_function_decl (fndecl, /*update_methods=*/false);
19250 
19251   if (!access_ok)
19252     {
19253       if (!(complain & tf_error))
19254 	{
19255 	  /* Remember to reinstantiate when we're out of SFINAE so the user
19256 	     can see the errors.  */
19257 	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
19258 	}
19259       return error_mark_node;
19260     }
19261   return fndecl;
19262 }
19263 
19264 /* Wrapper for instantiate_template_1.  */
19265 
19266 tree
19267 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
19268 {
19269   tree ret;
19270   timevar_push (TV_TEMPLATE_INST);
19271   ret = instantiate_template_1 (tmpl, orig_args,  complain);
19272   timevar_pop (TV_TEMPLATE_INST);
19273   return ret;
19274 }
19275 
19276 /* Instantiate the alias template TMPL with ARGS.  Also push a template
19277    instantiation level, which instantiate_template doesn't do because
19278    functions and variables have sufficient context established by the
19279    callers.  */
19280 
19281 static tree
19282 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
19283 {
19284   if (tmpl == error_mark_node || args == error_mark_node)
19285     return error_mark_node;
19286   if (!push_tinst_level (tmpl, args))
19287     return error_mark_node;
19288 
19289   args =
19290     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
19291 				     args, tmpl, complain,
19292 				     /*require_all_args=*/true,
19293 				     /*use_default_args=*/true);
19294 
19295   tree r = instantiate_template (tmpl, args, complain);
19296   pop_tinst_level ();
19297 
19298   return r;
19299 }
19300 
19301 /* PARM is a template parameter pack for FN.  Returns true iff
19302    PARM is used in a deducible way in the argument list of FN.  */
19303 
19304 static bool
19305 pack_deducible_p (tree parm, tree fn)
19306 {
19307   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
19308   for (; t; t = TREE_CHAIN (t))
19309     {
19310       tree type = TREE_VALUE (t);
19311       tree packs;
19312       if (!PACK_EXPANSION_P (type))
19313 	continue;
19314       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
19315 	   packs; packs = TREE_CHAIN (packs))
19316 	if (template_args_equal (TREE_VALUE (packs), parm))
19317 	  {
19318 	    /* The template parameter pack is used in a function parameter
19319 	       pack.  If this is the end of the parameter list, the
19320 	       template parameter pack is deducible.  */
19321 	    if (TREE_CHAIN (t) == void_list_node)
19322 	      return true;
19323 	    else
19324 	      /* Otherwise, not.  Well, it could be deduced from
19325 		 a non-pack parameter, but doing so would end up with
19326 		 a deduction mismatch, so don't bother.  */
19327 	      return false;
19328 	  }
19329     }
19330   /* The template parameter pack isn't used in any function parameter
19331      packs, but it might be used deeper, e.g. tuple<Args...>.  */
19332   return true;
19333 }
19334 
19335 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
19336    NARGS elements of the arguments that are being used when calling
19337    it.  TARGS is a vector into which the deduced template arguments
19338    are placed.
19339 
19340    Returns either a FUNCTION_DECL for the matching specialization of FN or
19341    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
19342    true, diagnostics will be printed to explain why it failed.
19343 
19344    If FN is a conversion operator, or we are trying to produce a specific
19345    specialization, RETURN_TYPE is the return type desired.
19346 
19347    The EXPLICIT_TARGS are explicit template arguments provided via a
19348    template-id.
19349 
19350    The parameter STRICT is one of:
19351 
19352    DEDUCE_CALL:
19353      We are deducing arguments for a function call, as in
19354      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
19355      deducing arguments for a call to the result of a conversion
19356      function template, as in [over.call.object].
19357 
19358    DEDUCE_CONV:
19359      We are deducing arguments for a conversion function, as in
19360      [temp.deduct.conv].
19361 
19362    DEDUCE_EXACT:
19363      We are deducing arguments when doing an explicit instantiation
19364      as in [temp.explicit], when determining an explicit specialization
19365      as in [temp.expl.spec], or when taking the address of a function
19366      template, as in [temp.deduct.funcaddr].  */
19367 
19368 tree
19369 fn_type_unification (tree fn,
19370 		     tree explicit_targs,
19371 		     tree targs,
19372 		     const tree *args,
19373 		     unsigned int nargs,
19374 		     tree return_type,
19375 		     unification_kind_t strict,
19376 		     int flags,
19377 		     bool explain_p,
19378 		     bool decltype_p)
19379 {
19380   tree parms;
19381   tree fntype;
19382   tree decl = NULL_TREE;
19383   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
19384   bool ok;
19385   static int deduction_depth;
19386 
19387   tree orig_fn = fn;
19388   if (flag_new_inheriting_ctors)
19389     fn = strip_inheriting_ctors (fn);
19390 
19391   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
19392   tree r = error_mark_node;
19393 
19394   tree full_targs = targs;
19395   if (TMPL_ARGS_DEPTH (targs)
19396       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
19397     full_targs = (add_outermost_template_args
19398 		  (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
19399 		   targs));
19400 
19401   if (decltype_p)
19402     complain |= tf_decltype;
19403 
19404   /* In C++0x, it's possible to have a function template whose type depends
19405      on itself recursively.  This is most obvious with decltype, but can also
19406      occur with enumeration scope (c++/48969).  So we need to catch infinite
19407      recursion and reject the substitution at deduction time; this function
19408      will return error_mark_node for any repeated substitution.
19409 
19410      This also catches excessive recursion such as when f<N> depends on
19411      f<N-1> across all integers, and returns error_mark_node for all the
19412      substitutions back up to the initial one.
19413 
19414      This is, of course, not reentrant.  */
19415   if (excessive_deduction_depth)
19416     return error_mark_node;
19417   ++deduction_depth;
19418 
19419   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
19420 
19421   fntype = TREE_TYPE (fn);
19422   if (explicit_targs)
19423     {
19424       /* [temp.deduct]
19425 
19426 	 The specified template arguments must match the template
19427 	 parameters in kind (i.e., type, nontype, template), and there
19428 	 must not be more arguments than there are parameters;
19429 	 otherwise type deduction fails.
19430 
19431 	 Nontype arguments must match the types of the corresponding
19432 	 nontype template parameters, or must be convertible to the
19433 	 types of the corresponding nontype parameters as specified in
19434 	 _temp.arg.nontype_, otherwise type deduction fails.
19435 
19436 	 All references in the function type of the function template
19437 	 to the corresponding template parameters are replaced by the
19438 	 specified template argument values.  If a substitution in a
19439 	 template parameter or in the function type of the function
19440 	 template results in an invalid type, type deduction fails.  */
19441       int i, len = TREE_VEC_LENGTH (tparms);
19442       location_t loc = input_location;
19443       bool incomplete = false;
19444 
19445       if (explicit_targs == error_mark_node)
19446 	goto fail;
19447 
19448       if (TMPL_ARGS_DEPTH (explicit_targs)
19449 	  < TMPL_ARGS_DEPTH (full_targs))
19450 	explicit_targs = add_outermost_template_args (full_targs,
19451 						      explicit_targs);
19452 
19453       /* Adjust any explicit template arguments before entering the
19454 	 substitution context.  */
19455       explicit_targs
19456 	= (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
19457 				  complain,
19458 				  /*require_all_args=*/false,
19459 				  /*use_default_args=*/false));
19460       if (explicit_targs == error_mark_node)
19461 	goto fail;
19462 
19463       /* Substitute the explicit args into the function type.  This is
19464 	 necessary so that, for instance, explicitly declared function
19465 	 arguments can match null pointed constants.  If we were given
19466 	 an incomplete set of explicit args, we must not do semantic
19467 	 processing during substitution as we could create partial
19468 	 instantiations.  */
19469       for (i = 0; i < len; i++)
19470         {
19471           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
19472           bool parameter_pack = false;
19473 	  tree targ = TREE_VEC_ELT (explicit_targs, i);
19474 
19475           /* Dig out the actual parm.  */
19476           if (TREE_CODE (parm) == TYPE_DECL
19477               || TREE_CODE (parm) == TEMPLATE_DECL)
19478             {
19479               parm = TREE_TYPE (parm);
19480               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
19481             }
19482           else if (TREE_CODE (parm) == PARM_DECL)
19483             {
19484               parm = DECL_INITIAL (parm);
19485               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
19486             }
19487 
19488 	  if (!parameter_pack && targ == NULL_TREE)
19489 	    /* No explicit argument for this template parameter.  */
19490 	    incomplete = true;
19491 
19492           if (parameter_pack && pack_deducible_p (parm, fn))
19493             {
19494               /* Mark the argument pack as "incomplete". We could
19495                  still deduce more arguments during unification.
19496 	         We remove this mark in type_unification_real.  */
19497               if (targ)
19498                 {
19499                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
19500                   ARGUMENT_PACK_EXPLICIT_ARGS (targ)
19501                     = ARGUMENT_PACK_ARGS (targ);
19502                 }
19503 
19504               /* We have some incomplete argument packs.  */
19505               incomplete = true;
19506             }
19507         }
19508 
19509       if (!push_tinst_level (fn, explicit_targs))
19510 	{
19511 	  excessive_deduction_depth = true;
19512 	  goto fail;
19513 	}
19514       processing_template_decl += incomplete;
19515       input_location = DECL_SOURCE_LOCATION (fn);
19516       /* Ignore any access checks; we'll see them again in
19517 	 instantiate_template and they might have the wrong
19518 	 access path at this point.  */
19519       push_deferring_access_checks (dk_deferred);
19520       fntype = tsubst (TREE_TYPE (fn), explicit_targs,
19521 		       complain | tf_partial | tf_fndecl_type, NULL_TREE);
19522       pop_deferring_access_checks ();
19523       input_location = loc;
19524       processing_template_decl -= incomplete;
19525       pop_tinst_level ();
19526 
19527       if (fntype == error_mark_node)
19528 	goto fail;
19529 
19530       /* Place the explicitly specified arguments in TARGS.  */
19531       explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
19532       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
19533 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
19534     }
19535 
19536   /* Never do unification on the 'this' parameter.  */
19537   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
19538 
19539   if (return_type && strict == DEDUCE_CALL)
19540     {
19541       /* We're deducing for a call to the result of a template conversion
19542          function.  The parms we really want are in return_type.  */
19543       if (POINTER_TYPE_P (return_type))
19544 	return_type = TREE_TYPE (return_type);
19545       parms = TYPE_ARG_TYPES (return_type);
19546     }
19547   else if (return_type)
19548     {
19549       tree *new_args;
19550 
19551       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
19552       new_args = XALLOCAVEC (tree, nargs + 1);
19553       new_args[0] = return_type;
19554       memcpy (new_args + 1, args, nargs * sizeof (tree));
19555       args = new_args;
19556       ++nargs;
19557     }
19558 
19559   /* We allow incomplete unification without an error message here
19560      because the standard doesn't seem to explicitly prohibit it.  Our
19561      callers must be ready to deal with unification failures in any
19562      event.  */
19563 
19564   /* If we aren't explaining yet, push tinst context so we can see where
19565      any errors (e.g. from class instantiations triggered by instantiation
19566      of default template arguments) come from.  If we are explaining, this
19567      context is redundant.  */
19568   if (!explain_p && !push_tinst_level (fn, targs))
19569     {
19570       excessive_deduction_depth = true;
19571       goto fail;
19572     }
19573 
19574   /* type_unification_real will pass back any access checks from default
19575      template argument substitution.  */
19576   vec<deferred_access_check, va_gc> *checks;
19577   checks = NULL;
19578 
19579   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
19580 			       full_targs, parms, args, nargs, /*subr=*/0,
19581 			       strict, flags, &checks, explain_p);
19582   if (!explain_p)
19583     pop_tinst_level ();
19584   if (!ok)
19585     goto fail;
19586 
19587   /* Now that we have bindings for all of the template arguments,
19588      ensure that the arguments deduced for the template template
19589      parameters have compatible template parameter lists.  We cannot
19590      check this property before we have deduced all template
19591      arguments, because the template parameter types of a template
19592      template parameter might depend on prior template parameters
19593      deduced after the template template parameter.  The following
19594      ill-formed example illustrates this issue:
19595 
19596        template<typename T, template<T> class C> void f(C<5>, T);
19597 
19598        template<int N> struct X {};
19599 
19600        void g() {
19601          f(X<5>(), 5l); // error: template argument deduction fails
19602        }
19603 
19604      The template parameter list of 'C' depends on the template type
19605      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
19606      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
19607      time that we deduce 'C'.  */
19608   if (!template_template_parm_bindings_ok_p
19609            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
19610     {
19611       unify_inconsistent_template_template_parameters (explain_p);
19612       goto fail;
19613     }
19614 
19615   /* All is well so far.  Now, check:
19616 
19617      [temp.deduct]
19618 
19619      When all template arguments have been deduced, all uses of
19620      template parameters in nondeduced contexts are replaced with
19621      the corresponding deduced argument values.  If the
19622      substitution results in an invalid type, as described above,
19623      type deduction fails.  */
19624   if (!push_tinst_level (fn, targs))
19625     {
19626       excessive_deduction_depth = true;
19627       goto fail;
19628     }
19629 
19630   /* Also collect access checks from the instantiation.  */
19631   reopen_deferring_access_checks (checks);
19632 
19633   decl = instantiate_template (fn, targs, complain);
19634 
19635   checks = get_deferred_access_checks ();
19636   pop_deferring_access_checks ();
19637 
19638   pop_tinst_level ();
19639 
19640   if (decl == error_mark_node)
19641     goto fail;
19642 
19643   /* Now perform any access checks encountered during substitution.  */
19644   push_access_scope (decl);
19645   ok = perform_access_checks (checks, complain);
19646   pop_access_scope (decl);
19647   if (!ok)
19648     goto fail;
19649 
19650   /* If we're looking for an exact match, check that what we got
19651      is indeed an exact match.  It might not be if some template
19652      parameters are used in non-deduced contexts.  But don't check
19653      for an exact match if we have dependent template arguments;
19654      in that case we're doing partial ordering, and we already know
19655      that we have two candidates that will provide the actual type.  */
19656   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
19657     {
19658       tree substed = TREE_TYPE (decl);
19659       unsigned int i;
19660 
19661       tree sarg
19662 	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
19663       if (return_type)
19664 	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
19665       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
19666 	if (!same_type_p (args[i], TREE_VALUE (sarg)))
19667 	  {
19668 	    unify_type_mismatch (explain_p, args[i],
19669 				 TREE_VALUE (sarg));
19670 	    goto fail;
19671 	  }
19672     }
19673 
19674   /* After doing deduction with the inherited constructor, actually return an
19675      instantiation of the inheriting constructor.  */
19676   if (orig_fn != fn)
19677     decl = instantiate_template (orig_fn, targs, complain);
19678 
19679   r = decl;
19680 
19681  fail:
19682   --deduction_depth;
19683   if (excessive_deduction_depth)
19684     {
19685       if (deduction_depth == 0)
19686 	/* Reset once we're all the way out.  */
19687 	excessive_deduction_depth = false;
19688     }
19689 
19690   return r;
19691 }
19692 
19693 /* Adjust types before performing type deduction, as described in
19694    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
19695    sections are symmetric.  PARM is the type of a function parameter
19696    or the return type of the conversion function.  ARG is the type of
19697    the argument passed to the call, or the type of the value
19698    initialized with the result of the conversion function.
19699    ARG_EXPR is the original argument expression, which may be null.  */
19700 
19701 static int
19702 maybe_adjust_types_for_deduction (unification_kind_t strict,
19703 				  tree* parm,
19704 				  tree* arg,
19705 				  tree arg_expr)
19706 {
19707   int result = 0;
19708 
19709   switch (strict)
19710     {
19711     case DEDUCE_CALL:
19712       break;
19713 
19714     case DEDUCE_CONV:
19715       /* Swap PARM and ARG throughout the remainder of this
19716 	 function; the handling is precisely symmetric since PARM
19717 	 will initialize ARG rather than vice versa.  */
19718       std::swap (parm, arg);
19719       break;
19720 
19721     case DEDUCE_EXACT:
19722       /* Core issue #873: Do the DR606 thing (see below) for these cases,
19723 	 too, but here handle it by stripping the reference from PARM
19724 	 rather than by adding it to ARG.  */
19725       if (TREE_CODE (*parm) == REFERENCE_TYPE
19726 	  && TYPE_REF_IS_RVALUE (*parm)
19727 	  && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
19728 	  && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
19729 	  && TREE_CODE (*arg) == REFERENCE_TYPE
19730 	  && !TYPE_REF_IS_RVALUE (*arg))
19731 	*parm = TREE_TYPE (*parm);
19732       /* Nothing else to do in this case.  */
19733       return 0;
19734 
19735     default:
19736       gcc_unreachable ();
19737     }
19738 
19739   if (TREE_CODE (*parm) != REFERENCE_TYPE)
19740     {
19741       /* [temp.deduct.call]
19742 
19743 	 If P is not a reference type:
19744 
19745 	 --If A is an array type, the pointer type produced by the
19746 	 array-to-pointer standard conversion (_conv.array_) is
19747 	 used in place of A for type deduction; otherwise,
19748 
19749 	 --If A is a function type, the pointer type produced by
19750 	 the function-to-pointer standard conversion
19751 	 (_conv.func_) is used in place of A for type deduction;
19752 	 otherwise,
19753 
19754 	 --If A is a cv-qualified type, the top level
19755 	 cv-qualifiers of A's type are ignored for type
19756 	 deduction.  */
19757       if (TREE_CODE (*arg) == ARRAY_TYPE)
19758 	*arg = build_pointer_type (TREE_TYPE (*arg));
19759       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
19760 	*arg = build_pointer_type (*arg);
19761       else
19762 	*arg = TYPE_MAIN_VARIANT (*arg);
19763     }
19764 
19765   /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
19766      reference to a cv-unqualified template parameter that does not represent a
19767      template parameter of a class template (during class template argument
19768      deduction (13.3.1.8)). If P is a forwarding reference and the argument is
19769      an lvalue, the type "lvalue reference to A" is used in place of A for type
19770      deduction. */
19771   if (TREE_CODE (*parm) == REFERENCE_TYPE
19772       && TYPE_REF_IS_RVALUE (*parm)
19773       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
19774       && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
19775       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
19776       && (arg_expr ? lvalue_p (arg_expr)
19777 	  /* try_one_overload doesn't provide an arg_expr, but
19778 	     functions are always lvalues.  */
19779 	  : TREE_CODE (*arg) == FUNCTION_TYPE))
19780     *arg = build_reference_type (*arg);
19781 
19782   /* [temp.deduct.call]
19783 
19784      If P is a cv-qualified type, the top level cv-qualifiers
19785      of P's type are ignored for type deduction.  If P is a
19786      reference type, the type referred to by P is used for
19787      type deduction.  */
19788   *parm = TYPE_MAIN_VARIANT (*parm);
19789   if (TREE_CODE (*parm) == REFERENCE_TYPE)
19790     {
19791       *parm = TREE_TYPE (*parm);
19792       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
19793     }
19794 
19795   /* DR 322. For conversion deduction, remove a reference type on parm
19796      too (which has been swapped into ARG).  */
19797   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
19798     *arg = TREE_TYPE (*arg);
19799 
19800   return result;
19801 }
19802 
19803 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
19804    template which does contain any deducible template parameters; check if
19805    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
19806    unify_one_argument.  */
19807 
19808 static int
19809 check_non_deducible_conversion (tree parm, tree arg, int strict,
19810 				int flags, bool explain_p)
19811 {
19812   tree type;
19813 
19814   if (!TYPE_P (arg))
19815     type = TREE_TYPE (arg);
19816   else
19817     type = arg;
19818 
19819   if (same_type_p (parm, type))
19820     return unify_success (explain_p);
19821 
19822   if (strict == DEDUCE_CONV)
19823     {
19824       if (can_convert_arg (type, parm, NULL_TREE, flags,
19825 			   explain_p ? tf_warning_or_error : tf_none))
19826 	return unify_success (explain_p);
19827     }
19828   else if (strict != DEDUCE_EXACT)
19829     {
19830       if (can_convert_arg (parm, type,
19831 			   TYPE_P (arg) ? NULL_TREE : arg,
19832 			   flags, explain_p ? tf_warning_or_error : tf_none))
19833 	return unify_success (explain_p);
19834     }
19835 
19836   if (strict == DEDUCE_EXACT)
19837     return unify_type_mismatch (explain_p, parm, arg);
19838   else
19839     return unify_arg_conversion (explain_p, parm, type, arg);
19840 }
19841 
19842 static bool uses_deducible_template_parms (tree type);
19843 
19844 /* Returns true iff the expression EXPR is one from which a template
19845    argument can be deduced.  In other words, if it's an undecorated
19846    use of a template non-type parameter.  */
19847 
19848 static bool
19849 deducible_expression (tree expr)
19850 {
19851   /* Strip implicit conversions.  */
19852   while (CONVERT_EXPR_P (expr))
19853     expr = TREE_OPERAND (expr, 0);
19854   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
19855 }
19856 
19857 /* Returns true iff the array domain DOMAIN uses a template parameter in a
19858    deducible way; that is, if it has a max value of <PARM> - 1.  */
19859 
19860 static bool
19861 deducible_array_bound (tree domain)
19862 {
19863   if (domain == NULL_TREE)
19864     return false;
19865 
19866   tree max = TYPE_MAX_VALUE (domain);
19867   if (TREE_CODE (max) != MINUS_EXPR)
19868     return false;
19869 
19870   return deducible_expression (TREE_OPERAND (max, 0));
19871 }
19872 
19873 /* Returns true iff the template arguments ARGS use a template parameter
19874    in a deducible way.  */
19875 
19876 static bool
19877 deducible_template_args (tree args)
19878 {
19879   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
19880     {
19881       bool deducible;
19882       tree elt = TREE_VEC_ELT (args, i);
19883       if (ARGUMENT_PACK_P (elt))
19884 	deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
19885       else
19886 	{
19887 	  if (PACK_EXPANSION_P (elt))
19888 	    elt = PACK_EXPANSION_PATTERN (elt);
19889 	  if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
19890 	    deducible = true;
19891 	  else if (TYPE_P (elt))
19892 	    deducible = uses_deducible_template_parms (elt);
19893 	  else
19894 	    deducible = deducible_expression (elt);
19895 	}
19896       if (deducible)
19897 	return true;
19898     }
19899   return false;
19900 }
19901 
19902 /* Returns true iff TYPE contains any deducible references to template
19903    parameters, as per 14.8.2.5.  */
19904 
19905 static bool
19906 uses_deducible_template_parms (tree type)
19907 {
19908   if (PACK_EXPANSION_P (type))
19909     type = PACK_EXPANSION_PATTERN (type);
19910 
19911   /* T
19912      cv-list T
19913      TT<T>
19914      TT<i>
19915      TT<> */
19916   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19917       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
19918     return true;
19919 
19920   /* T*
19921      T&
19922      T&&  */
19923   if (POINTER_TYPE_P (type))
19924     return uses_deducible_template_parms (TREE_TYPE (type));
19925 
19926   /* T[integer-constant ]
19927      type [i]  */
19928   if (TREE_CODE (type) == ARRAY_TYPE)
19929     return (uses_deducible_template_parms (TREE_TYPE (type))
19930 	    || deducible_array_bound (TYPE_DOMAIN (type)));
19931 
19932   /* T type ::*
19933      type T::*
19934      T T::*
19935      T (type ::*)()
19936      type (T::*)()
19937      type (type ::*)(T)
19938      type (T::*)(T)
19939      T (type ::*)(T)
19940      T (T::*)()
19941      T (T::*)(T) */
19942   if (TYPE_PTRMEM_P (type))
19943     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
19944 	    || (uses_deducible_template_parms
19945 		(TYPE_PTRMEM_POINTED_TO_TYPE (type))));
19946 
19947   /* template-name <T> (where template-name refers to a class template)
19948      template-name <i> (where template-name refers to a class template) */
19949   if (CLASS_TYPE_P (type)
19950       && CLASSTYPE_TEMPLATE_INFO (type)
19951       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
19952     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
19953 				    (CLASSTYPE_TI_ARGS (type)));
19954 
19955   /* type (T)
19956      T()
19957      T(T)  */
19958   if (TREE_CODE (type) == FUNCTION_TYPE
19959       || TREE_CODE (type) == METHOD_TYPE)
19960     {
19961       if (uses_deducible_template_parms (TREE_TYPE (type)))
19962 	return true;
19963       tree parm = TYPE_ARG_TYPES (type);
19964       if (TREE_CODE (type) == METHOD_TYPE)
19965 	parm = TREE_CHAIN (parm);
19966       for (; parm; parm = TREE_CHAIN (parm))
19967 	if (uses_deducible_template_parms (TREE_VALUE (parm)))
19968 	  return true;
19969     }
19970 
19971   return false;
19972 }
19973 
19974 /* Subroutine of type_unification_real and unify_pack_expansion to
19975    handle unification of a single P/A pair.  Parameters are as
19976    for those functions.  */
19977 
19978 static int
19979 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
19980 		    int subr, unification_kind_t strict,
19981 		    bool explain_p)
19982 {
19983   tree arg_expr = NULL_TREE;
19984   int arg_strict;
19985 
19986   if (arg == error_mark_node || parm == error_mark_node)
19987     return unify_invalid (explain_p);
19988   if (arg == unknown_type_node)
19989     /* We can't deduce anything from this, but we might get all the
19990        template args from other function args.  */
19991     return unify_success (explain_p);
19992 
19993   /* Implicit conversions (Clause 4) will be performed on a function
19994      argument to convert it to the type of the corresponding function
19995      parameter if the parameter type contains no template-parameters that
19996      participate in template argument deduction.  */
19997   if (strict != DEDUCE_EXACT
19998       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
19999     /* For function parameters with no deducible template parameters,
20000        just return.  We'll check non-dependent conversions later.  */
20001     return unify_success (explain_p);
20002 
20003   switch (strict)
20004     {
20005     case DEDUCE_CALL:
20006       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
20007 		    | UNIFY_ALLOW_MORE_CV_QUAL
20008 		    | UNIFY_ALLOW_DERIVED);
20009       break;
20010 
20011     case DEDUCE_CONV:
20012       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
20013       break;
20014 
20015     case DEDUCE_EXACT:
20016       arg_strict = UNIFY_ALLOW_NONE;
20017       break;
20018 
20019     default:
20020       gcc_unreachable ();
20021     }
20022 
20023   /* We only do these transformations if this is the top-level
20024      parameter_type_list in a call or declaration matching; in other
20025      situations (nested function declarators, template argument lists) we
20026      won't be comparing a type to an expression, and we don't do any type
20027      adjustments.  */
20028   if (!subr)
20029     {
20030       if (!TYPE_P (arg))
20031 	{
20032 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
20033 	  if (type_unknown_p (arg))
20034 	    {
20035 	      /* [temp.deduct.type] A template-argument can be
20036 		 deduced from a pointer to function or pointer
20037 		 to member function argument if the set of
20038 		 overloaded functions does not contain function
20039 		 templates and at most one of a set of
20040 		 overloaded functions provides a unique
20041 		 match.  */
20042 	      resolve_overloaded_unification (tparms, targs, parm,
20043 					      arg, strict,
20044 					      arg_strict, explain_p);
20045 	      /* If a unique match was not found, this is a
20046 	         non-deduced context, so we still succeed. */
20047 	      return unify_success (explain_p);
20048 	    }
20049 
20050 	  arg_expr = arg;
20051 	  arg = unlowered_expr_type (arg);
20052 	  if (arg == error_mark_node)
20053 	    return unify_invalid (explain_p);
20054 	}
20055 
20056       arg_strict |=
20057 	maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
20058     }
20059   else
20060     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
20061 	!= (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
20062       return unify_template_argument_mismatch (explain_p, parm, arg);
20063 
20064   /* For deduction from an init-list we need the actual list.  */
20065   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
20066     arg = arg_expr;
20067   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
20068 }
20069 
20070 /* for_each_template_parm callback that always returns 0.  */
20071 
20072 static int
20073 zero_r (tree, void *)
20074 {
20075   return 0;
20076 }
20077 
20078 /* for_each_template_parm any_fn callback to handle deduction of a template
20079    type argument from the type of an array bound.  */
20080 
20081 static int
20082 array_deduction_r (tree t, void *data)
20083 {
20084   tree_pair_p d = (tree_pair_p)data;
20085   tree &tparms = d->purpose;
20086   tree &targs = d->value;
20087 
20088   if (TREE_CODE (t) == ARRAY_TYPE)
20089     if (tree dom = TYPE_DOMAIN (t))
20090       if (tree max = TYPE_MAX_VALUE (dom))
20091 	{
20092 	  if (TREE_CODE (max) == MINUS_EXPR)
20093 	    max = TREE_OPERAND (max, 0);
20094 	  if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
20095 	    unify (tparms, targs, TREE_TYPE (max), size_type_node,
20096 		   UNIFY_ALLOW_NONE, /*explain*/false);
20097 	}
20098 
20099   /* Keep walking.  */
20100   return 0;
20101 }
20102 
20103 /* Try to deduce any not-yet-deduced template type arguments from the type of
20104    an array bound.  This is handled separately from unify because 14.8.2.5 says
20105    "The type of a type parameter is only deduced from an array bound if it is
20106    not otherwise deduced."  */
20107 
20108 static void
20109 try_array_deduction (tree tparms, tree targs, tree parm)
20110 {
20111   tree_pair_s data = { tparms, targs };
20112   hash_set<tree> visited;
20113   for_each_template_parm (parm, zero_r, &data, &visited,
20114 			  /*nondeduced*/false, array_deduction_r);
20115 }
20116 
20117 /* Most parms like fn_type_unification.
20118 
20119    If SUBR is 1, we're being called recursively (to unify the
20120    arguments of a function or method parameter of a function
20121    template).
20122 
20123    CHECKS is a pointer to a vector of access checks encountered while
20124    substituting default template arguments.  */
20125 
20126 static int
20127 type_unification_real (tree tparms,
20128 		       tree full_targs,
20129 		       tree xparms,
20130 		       const tree *xargs,
20131 		       unsigned int xnargs,
20132 		       int subr,
20133 		       unification_kind_t strict,
20134 		       int flags,
20135 		       vec<deferred_access_check, va_gc> **checks,
20136 		       bool explain_p)
20137 {
20138   tree parm, arg;
20139   int i;
20140   int ntparms = TREE_VEC_LENGTH (tparms);
20141   int saw_undeduced = 0;
20142   tree parms;
20143   const tree *args;
20144   unsigned int nargs;
20145   unsigned int ia;
20146 
20147   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
20148   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
20149   gcc_assert (ntparms > 0);
20150 
20151   tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
20152 
20153   /* Reset the number of non-defaulted template arguments contained
20154      in TARGS.  */
20155   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
20156 
20157  again:
20158   parms = xparms;
20159   args = xargs;
20160   nargs = xnargs;
20161 
20162   ia = 0;
20163   while (parms && parms != void_list_node
20164 	 && ia < nargs)
20165     {
20166       parm = TREE_VALUE (parms);
20167 
20168       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20169 	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
20170 	/* For a function parameter pack that occurs at the end of the
20171 	   parameter-declaration-list, the type A of each remaining
20172 	   argument of the call is compared with the type P of the
20173 	   declarator-id of the function parameter pack.  */
20174 	break;
20175 
20176       parms = TREE_CHAIN (parms);
20177 
20178       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20179 	/* For a function parameter pack that does not occur at the
20180 	   end of the parameter-declaration-list, the type of the
20181 	   parameter pack is a non-deduced context.  */
20182 	continue;
20183 
20184       arg = args[ia];
20185       ++ia;
20186 
20187       if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
20188 			      explain_p))
20189 	return 1;
20190     }
20191 
20192   if (parms
20193       && parms != void_list_node
20194       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
20195     {
20196       /* Unify the remaining arguments with the pack expansion type.  */
20197       tree argvec;
20198       tree parmvec = make_tree_vec (1);
20199 
20200       /* Allocate a TREE_VEC and copy in all of the arguments */
20201       argvec = make_tree_vec (nargs - ia);
20202       for (i = 0; ia < nargs; ++ia, ++i)
20203 	TREE_VEC_ELT (argvec, i) = args[ia];
20204 
20205       /* Copy the parameter into parmvec.  */
20206       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
20207       if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
20208                                 /*subr=*/subr, explain_p))
20209         return 1;
20210 
20211       /* Advance to the end of the list of parameters.  */
20212       parms = TREE_CHAIN (parms);
20213     }
20214 
20215   /* Fail if we've reached the end of the parm list, and more args
20216      are present, and the parm list isn't variadic.  */
20217   if (ia < nargs && parms == void_list_node)
20218     return unify_too_many_arguments (explain_p, nargs, ia);
20219   /* Fail if parms are left and they don't have default values and
20220      they aren't all deduced as empty packs (c++/57397).  This is
20221      consistent with sufficient_parms_p.  */
20222   if (parms && parms != void_list_node
20223       && TREE_PURPOSE (parms) == NULL_TREE)
20224     {
20225       unsigned int count = nargs;
20226       tree p = parms;
20227       bool type_pack_p;
20228       do
20229 	{
20230 	  type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
20231 	  if (!type_pack_p)
20232 	    count++;
20233 	  p = TREE_CHAIN (p);
20234 	}
20235       while (p && p != void_list_node);
20236       if (count != nargs)
20237 	return unify_too_few_arguments (explain_p, ia, count,
20238 					type_pack_p);
20239     }
20240 
20241   if (!subr)
20242     {
20243       tsubst_flags_t complain = (explain_p
20244 				 ? tf_warning_or_error
20245 				 : tf_none);
20246       bool tried_array_deduction = (cxx_dialect < cxx17);
20247 
20248       for (i = 0; i < ntparms; i++)
20249 	{
20250 	  tree targ = TREE_VEC_ELT (targs, i);
20251 	  tree tparm = TREE_VEC_ELT (tparms, i);
20252 
20253 	  /* Clear the "incomplete" flags on all argument packs now so that
20254 	     substituting them into later default arguments works.  */
20255 	  if (targ && ARGUMENT_PACK_P (targ))
20256             {
20257               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
20258               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
20259             }
20260 
20261 	  if (targ || tparm == error_mark_node)
20262 	    continue;
20263 	  tparm = TREE_VALUE (tparm);
20264 
20265 	  if (TREE_CODE (tparm) == TYPE_DECL
20266 	      && !tried_array_deduction)
20267 	    {
20268 	      try_array_deduction (tparms, targs, xparms);
20269 	      tried_array_deduction = true;
20270 	      if (TREE_VEC_ELT (targs, i))
20271 		continue;
20272 	    }
20273 
20274 	  /* If this is an undeduced nontype parameter that depends on
20275 	     a type parameter, try another pass; its type may have been
20276 	     deduced from a later argument than the one from which
20277 	     this parameter can be deduced.  */
20278 	  if (TREE_CODE (tparm) == PARM_DECL
20279 	      && uses_template_parms (TREE_TYPE (tparm))
20280 	      && saw_undeduced < 2)
20281 	    {
20282 	      saw_undeduced = 1;
20283 	      continue;
20284 	    }
20285 
20286 	  /* Core issue #226 (C++0x) [temp.deduct]:
20287 
20288 	     If a template argument has not been deduced, its
20289 	     default template argument, if any, is used.
20290 
20291 	     When we are in C++98 mode, TREE_PURPOSE will either
20292 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
20293 	     to explicitly check cxx_dialect here.  */
20294 	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
20295 	    /* OK, there is a default argument.  Wait until after the
20296 	       conversion check to do substitution.  */
20297 	    continue;
20298 
20299 	  /* If the type parameter is a parameter pack, then it will
20300 	     be deduced to an empty parameter pack.  */
20301 	  if (template_parameter_pack_p (tparm))
20302 	    {
20303 	      tree arg;
20304 
20305 	      if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
20306 		{
20307 		  arg = make_node (NONTYPE_ARGUMENT_PACK);
20308 		  TREE_CONSTANT (arg) = 1;
20309 		}
20310 	      else
20311 		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
20312 
20313 	      SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
20314 
20315 	      TREE_VEC_ELT (targs, i) = arg;
20316 	      continue;
20317 	    }
20318 
20319 	  return unify_parameter_deduction_failure (explain_p, tparm);
20320 	}
20321 
20322       /* DR 1391: All parameters have args, now check non-dependent parms for
20323 	 convertibility.  */
20324       if (saw_undeduced < 2)
20325 	for (ia = 0, parms = xparms, args = xargs, nargs = xnargs;
20326 	     parms && parms != void_list_node && ia < nargs; )
20327 	  {
20328 	    parm = TREE_VALUE (parms);
20329 
20330 	    if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20331 		&& (!TREE_CHAIN (parms)
20332 		    || TREE_CHAIN (parms) == void_list_node))
20333 	      /* For a function parameter pack that occurs at the end of the
20334 		 parameter-declaration-list, the type A of each remaining
20335 		 argument of the call is compared with the type P of the
20336 		 declarator-id of the function parameter pack.  */
20337 	      break;
20338 
20339 	    parms = TREE_CHAIN (parms);
20340 
20341 	    if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20342 	      /* For a function parameter pack that does not occur at the
20343 		 end of the parameter-declaration-list, the type of the
20344 		 parameter pack is a non-deduced context.  */
20345 	      continue;
20346 
20347 	    arg = args[ia];
20348 	    ++ia;
20349 
20350 	    if (uses_template_parms (parm))
20351 	      continue;
20352 	    if (check_non_deducible_conversion (parm, arg, strict, flags,
20353 						explain_p))
20354 	      return 1;
20355 	  }
20356 
20357       /* Now substitute into the default template arguments.  */
20358       for (i = 0; i < ntparms; i++)
20359 	{
20360 	  tree targ = TREE_VEC_ELT (targs, i);
20361 	  tree tparm = TREE_VEC_ELT (tparms, i);
20362 
20363 	  if (targ || tparm == error_mark_node)
20364 	    continue;
20365 	  tree parm = TREE_VALUE (tparm);
20366 	  tree arg = TREE_PURPOSE (tparm);
20367 	  reopen_deferring_access_checks (*checks);
20368 	  location_t save_loc = input_location;
20369 	  if (DECL_P (parm))
20370 	    input_location = DECL_SOURCE_LOCATION (parm);
20371 	  if (saw_undeduced == 1)
20372 	    ++processing_template_decl;
20373 
20374 	  if (saw_undeduced == 1
20375 	      && TREE_CODE (parm) == PARM_DECL
20376 	      && uses_template_parms (TREE_TYPE (parm)))
20377 	    {
20378 	      /* The type of this non-type parameter depends on undeduced
20379 		 parameters.  Don't try to use its default argument yet,
20380 		 but do check whether the arguments we already have cause
20381 		 substitution failure, so that that happens before we try
20382 		 later default arguments (78489).  */
20383 	      tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
20384 				  NULL_TREE);
20385 	      if (type == error_mark_node)
20386 		arg = error_mark_node;
20387 	      else
20388 		arg = NULL_TREE;
20389 	    }
20390 	  else
20391 	    {
20392 	      arg = tsubst_template_arg (arg, full_targs, complain, NULL_TREE);
20393 
20394 	      if (!uses_template_parms (arg))
20395 		arg = convert_template_argument (parm, arg, full_targs,
20396 						 complain, i, NULL_TREE);
20397 	      else if (saw_undeduced == 1)
20398 		arg = NULL_TREE;
20399 	      else
20400 		arg = error_mark_node;
20401 	    }
20402 
20403 	  if (saw_undeduced == 1)
20404 	    --processing_template_decl;
20405 	  input_location = save_loc;
20406 	  *checks = get_deferred_access_checks ();
20407 	  pop_deferring_access_checks ();
20408 
20409 	  if (arg == error_mark_node)
20410 	    return 1;
20411 	  else if (arg)
20412 	    {
20413 	      TREE_VEC_ELT (targs, i) = arg;
20414 	      /* The position of the first default template argument,
20415 		 is also the number of non-defaulted arguments in TARGS.
20416 		 Record that.  */
20417 	      if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20418 		SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
20419 	    }
20420 	}
20421 
20422       if (saw_undeduced++ == 1)
20423 	goto again;
20424     }
20425 
20426   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20427     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
20428 
20429   return unify_success (explain_p);
20430 }
20431 
20432 /* Subroutine of type_unification_real.  Args are like the variables
20433    at the call site.  ARG is an overloaded function (or template-id);
20434    we try deducing template args from each of the overloads, and if
20435    only one succeeds, we go with that.  Modifies TARGS and returns
20436    true on success.  */
20437 
20438 static bool
20439 resolve_overloaded_unification (tree tparms,
20440 				tree targs,
20441 				tree parm,
20442 				tree arg,
20443 				unification_kind_t strict,
20444 				int sub_strict,
20445 			        bool explain_p)
20446 {
20447   tree tempargs = copy_node (targs);
20448   int good = 0;
20449   tree goodfn = NULL_TREE;
20450   bool addr_p;
20451 
20452   if (TREE_CODE (arg) == ADDR_EXPR)
20453     {
20454       arg = TREE_OPERAND (arg, 0);
20455       addr_p = true;
20456     }
20457   else
20458     addr_p = false;
20459 
20460   if (TREE_CODE (arg) == COMPONENT_REF)
20461     /* Handle `&x' where `x' is some static or non-static member
20462        function name.  */
20463     arg = TREE_OPERAND (arg, 1);
20464 
20465   if (TREE_CODE (arg) == OFFSET_REF)
20466     arg = TREE_OPERAND (arg, 1);
20467 
20468   /* Strip baselink information.  */
20469   if (BASELINK_P (arg))
20470     arg = BASELINK_FUNCTIONS (arg);
20471 
20472   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
20473     {
20474       /* If we got some explicit template args, we need to plug them into
20475 	 the affected templates before we try to unify, in case the
20476 	 explicit args will completely resolve the templates in question.  */
20477 
20478       int ok = 0;
20479       tree expl_subargs = TREE_OPERAND (arg, 1);
20480       arg = TREE_OPERAND (arg, 0);
20481 
20482       for (lkp_iterator iter (arg); iter; ++iter)
20483 	{
20484 	  tree fn = *iter;
20485 	  tree subargs, elem;
20486 
20487 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
20488 	    continue;
20489 
20490 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20491 					   expl_subargs, NULL_TREE, tf_none,
20492 					   /*require_all_args=*/true,
20493 					   /*use_default_args=*/true);
20494 	  if (subargs != error_mark_node
20495 	      && !any_dependent_template_arguments_p (subargs))
20496 	    {
20497 	      elem = TREE_TYPE (instantiate_template (fn, subargs, tf_none));
20498 	      if (try_one_overload (tparms, targs, tempargs, parm,
20499 				    elem, strict, sub_strict, addr_p, explain_p)
20500 		  && (!goodfn || !same_type_p (goodfn, elem)))
20501 		{
20502 		  goodfn = elem;
20503 		  ++good;
20504 		}
20505 	    }
20506 	  else if (subargs)
20507 	    ++ok;
20508 	}
20509       /* If no templates (or more than one) are fully resolved by the
20510 	 explicit arguments, this template-id is a non-deduced context; it
20511 	 could still be OK if we deduce all template arguments for the
20512 	 enclosing call through other arguments.  */
20513       if (good != 1)
20514 	good = ok;
20515     }
20516   else if (TREE_CODE (arg) != OVERLOAD
20517 	   && TREE_CODE (arg) != FUNCTION_DECL)
20518     /* If ARG is, for example, "(0, &f)" then its type will be unknown
20519        -- but the deduction does not succeed because the expression is
20520        not just the function on its own.  */
20521     return false;
20522   else
20523     for (lkp_iterator iter (arg); iter; ++iter)
20524       {
20525 	tree fn = *iter;
20526 	if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
20527 			      strict, sub_strict, addr_p, explain_p)
20528 	    && (!goodfn || !decls_match (goodfn, fn)))
20529 	  {
20530 	    goodfn = fn;
20531 	    ++good;
20532 	  }
20533       }
20534 
20535   /* [temp.deduct.type] A template-argument can be deduced from a pointer
20536      to function or pointer to member function argument if the set of
20537      overloaded functions does not contain function templates and at most
20538      one of a set of overloaded functions provides a unique match.
20539 
20540      So if we found multiple possibilities, we return success but don't
20541      deduce anything.  */
20542 
20543   if (good == 1)
20544     {
20545       int i = TREE_VEC_LENGTH (targs);
20546       for (; i--; )
20547 	if (TREE_VEC_ELT (tempargs, i))
20548 	  {
20549 	    tree old = TREE_VEC_ELT (targs, i);
20550 	    tree new_ = TREE_VEC_ELT (tempargs, i);
20551 	    if (new_ && old && ARGUMENT_PACK_P (old)
20552 		&& ARGUMENT_PACK_EXPLICIT_ARGS (old))
20553 	      /* Don't forget explicit template arguments in a pack.  */
20554 	      ARGUMENT_PACK_EXPLICIT_ARGS (new_)
20555 		= ARGUMENT_PACK_EXPLICIT_ARGS (old);
20556 	    TREE_VEC_ELT (targs, i) = new_;
20557 	  }
20558     }
20559   if (good)
20560     return true;
20561 
20562   return false;
20563 }
20564 
20565 /* Core DR 115: In contexts where deduction is done and fails, or in
20566    contexts where deduction is not done, if a template argument list is
20567    specified and it, along with any default template arguments, identifies
20568    a single function template specialization, then the template-id is an
20569    lvalue for the function template specialization.  */
20570 
20571 tree
20572 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
20573 {
20574   tree expr, offset, baselink;
20575   bool addr;
20576 
20577   if (!type_unknown_p (orig_expr))
20578     return orig_expr;
20579 
20580   expr = orig_expr;
20581   addr = false;
20582   offset = NULL_TREE;
20583   baselink = NULL_TREE;
20584 
20585   if (TREE_CODE (expr) == ADDR_EXPR)
20586     {
20587       expr = TREE_OPERAND (expr, 0);
20588       addr = true;
20589     }
20590   if (TREE_CODE (expr) == OFFSET_REF)
20591     {
20592       offset = expr;
20593       expr = TREE_OPERAND (expr, 1);
20594     }
20595   if (BASELINK_P (expr))
20596     {
20597       baselink = expr;
20598       expr = BASELINK_FUNCTIONS (expr);
20599     }
20600 
20601   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
20602     {
20603       int good = 0;
20604       tree goodfn = NULL_TREE;
20605 
20606       /* If we got some explicit template args, we need to plug them into
20607 	 the affected templates before we try to unify, in case the
20608 	 explicit args will completely resolve the templates in question.  */
20609 
20610       tree expl_subargs = TREE_OPERAND (expr, 1);
20611       tree arg = TREE_OPERAND (expr, 0);
20612       tree badfn = NULL_TREE;
20613       tree badargs = NULL_TREE;
20614 
20615       for (lkp_iterator iter (arg); iter; ++iter)
20616 	{
20617 	  tree fn = *iter;
20618 	  tree subargs, elem;
20619 
20620 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
20621 	    continue;
20622 
20623 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20624 					   expl_subargs, NULL_TREE, tf_none,
20625 					   /*require_all_args=*/true,
20626 					   /*use_default_args=*/true);
20627 	  if (subargs != error_mark_node
20628 	      && !any_dependent_template_arguments_p (subargs))
20629 	    {
20630 	      elem = instantiate_template (fn, subargs, tf_none);
20631 	      if (elem == error_mark_node)
20632 		{
20633 		  badfn = fn;
20634 		  badargs = subargs;
20635 		}
20636 	      else if (elem && (!goodfn || !decls_match (goodfn, elem)))
20637 		{
20638 		  goodfn = elem;
20639 		  ++good;
20640 		}
20641 	    }
20642 	}
20643       if (good == 1)
20644 	{
20645 	  mark_used (goodfn);
20646 	  expr = goodfn;
20647 	  if (baselink)
20648 	    expr = build_baselink (BASELINK_BINFO (baselink),
20649 				   BASELINK_ACCESS_BINFO (baselink),
20650 				   expr, BASELINK_OPTYPE (baselink));
20651 	  if (offset)
20652 	    {
20653 	      tree base
20654 		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
20655 	      expr = build_offset_ref (base, expr, addr, complain);
20656 	    }
20657 	  if (addr)
20658 	    expr = cp_build_addr_expr (expr, complain);
20659 	  return expr;
20660 	}
20661       else if (good == 0 && badargs && (complain & tf_error))
20662 	/* There were no good options and at least one bad one, so let the
20663 	   user know what the problem is.  */
20664 	instantiate_template (badfn, badargs, complain);
20665     }
20666   return orig_expr;
20667 }
20668 
20669 /* Subroutine of resolve_overloaded_unification; does deduction for a single
20670    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
20671    different overloads deduce different arguments for a given parm.
20672    ADDR_P is true if the expression for which deduction is being
20673    performed was of the form "& fn" rather than simply "fn".
20674 
20675    Returns 1 on success.  */
20676 
20677 static int
20678 try_one_overload (tree tparms,
20679 		  tree orig_targs,
20680 		  tree targs,
20681 		  tree parm,
20682 		  tree arg,
20683 		  unification_kind_t strict,
20684 		  int sub_strict,
20685 		  bool addr_p,
20686 		  bool explain_p)
20687 {
20688   int nargs;
20689   tree tempargs;
20690   int i;
20691 
20692   if (arg == error_mark_node)
20693     return 0;
20694 
20695   /* [temp.deduct.type] A template-argument can be deduced from a pointer
20696      to function or pointer to member function argument if the set of
20697      overloaded functions does not contain function templates and at most
20698      one of a set of overloaded functions provides a unique match.
20699 
20700      So if this is a template, just return success.  */
20701 
20702   if (uses_template_parms (arg))
20703     return 1;
20704 
20705   if (TREE_CODE (arg) == METHOD_TYPE)
20706     arg = build_ptrmemfunc_type (build_pointer_type (arg));
20707   else if (addr_p)
20708     arg = build_pointer_type (arg);
20709 
20710   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
20711 
20712   /* We don't copy orig_targs for this because if we have already deduced
20713      some template args from previous args, unify would complain when we
20714      try to deduce a template parameter for the same argument, even though
20715      there isn't really a conflict.  */
20716   nargs = TREE_VEC_LENGTH (targs);
20717   tempargs = make_tree_vec (nargs);
20718 
20719   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
20720     return 0;
20721 
20722   /* First make sure we didn't deduce anything that conflicts with
20723      explicitly specified args.  */
20724   for (i = nargs; i--; )
20725     {
20726       tree elt = TREE_VEC_ELT (tempargs, i);
20727       tree oldelt = TREE_VEC_ELT (orig_targs, i);
20728 
20729       if (!elt)
20730 	/*NOP*/;
20731       else if (uses_template_parms (elt))
20732 	/* Since we're unifying against ourselves, we will fill in
20733 	   template args used in the function parm list with our own
20734 	   template parms.  Discard them.  */
20735 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
20736       else if (oldelt && ARGUMENT_PACK_P (oldelt))
20737 	{
20738 	  /* Check that the argument at each index of the deduced argument pack
20739 	     is equivalent to the corresponding explicitly specified argument.
20740 	     We may have deduced more arguments than were explicitly specified,
20741 	     and that's OK.  */
20742 
20743 	  /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
20744 	     that's wrong if we deduce the same argument pack from multiple
20745 	     function arguments: it's only incomplete the first time.  */
20746 
20747 	  tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
20748 	  tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
20749 
20750 	  if (TREE_VEC_LENGTH (deduced_pack)
20751 	      < TREE_VEC_LENGTH (explicit_pack))
20752 	    return 0;
20753 
20754 	  for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
20755 	    if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
20756 				      TREE_VEC_ELT (deduced_pack, j)))
20757 	      return 0;
20758 	}
20759       else if (oldelt && !template_args_equal (oldelt, elt))
20760 	return 0;
20761     }
20762 
20763   for (i = nargs; i--; )
20764     {
20765       tree elt = TREE_VEC_ELT (tempargs, i);
20766 
20767       if (elt)
20768 	TREE_VEC_ELT (targs, i) = elt;
20769     }
20770 
20771   return 1;
20772 }
20773 
20774 /* PARM is a template class (perhaps with unbound template
20775    parameters).  ARG is a fully instantiated type.  If ARG can be
20776    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
20777    TARGS are as for unify.  */
20778 
20779 static tree
20780 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
20781 		       bool explain_p)
20782 {
20783   tree copy_of_targs;
20784 
20785   if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
20786     return NULL_TREE;
20787   else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20788     /* Matches anything.  */;
20789   else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
20790 	   != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
20791     return NULL_TREE;
20792 
20793   /* We need to make a new template argument vector for the call to
20794      unify.  If we used TARGS, we'd clutter it up with the result of
20795      the attempted unification, even if this class didn't work out.
20796      We also don't want to commit ourselves to all the unifications
20797      we've already done, since unification is supposed to be done on
20798      an argument-by-argument basis.  In other words, consider the
20799      following pathological case:
20800 
20801        template <int I, int J, int K>
20802        struct S {};
20803 
20804        template <int I, int J>
20805        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
20806 
20807        template <int I, int J, int K>
20808        void f(S<I, J, K>, S<I, I, I>);
20809 
20810        void g() {
20811 	 S<0, 0, 0> s0;
20812 	 S<0, 1, 2> s2;
20813 
20814 	 f(s0, s2);
20815        }
20816 
20817      Now, by the time we consider the unification involving `s2', we
20818      already know that we must have `f<0, 0, 0>'.  But, even though
20819      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
20820      because there are two ways to unify base classes of S<0, 1, 2>
20821      with S<I, I, I>.  If we kept the already deduced knowledge, we
20822      would reject the possibility I=1.  */
20823   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
20824 
20825   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20826     {
20827       if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
20828 	return NULL_TREE;
20829       return arg;
20830     }
20831 
20832   /* If unification failed, we're done.  */
20833   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
20834 	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
20835     return NULL_TREE;
20836 
20837   return arg;
20838 }
20839 
20840 /* Given a template type PARM and a class type ARG, find the unique
20841    base type in ARG that is an instance of PARM.  We do not examine
20842    ARG itself; only its base-classes.  If there is not exactly one
20843    appropriate base class, return NULL_TREE.  PARM may be the type of
20844    a partial specialization, as well as a plain template type.  Used
20845    by unify.  */
20846 
20847 static enum template_base_result
20848 get_template_base (tree tparms, tree targs, tree parm, tree arg,
20849 		   bool explain_p, tree *result)
20850 {
20851   tree rval = NULL_TREE;
20852   tree binfo;
20853 
20854   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
20855 
20856   binfo = TYPE_BINFO (complete_type (arg));
20857   if (!binfo)
20858     {
20859       /* The type could not be completed.  */
20860       *result = NULL_TREE;
20861       return tbr_incomplete_type;
20862     }
20863 
20864   /* Walk in inheritance graph order.  The search order is not
20865      important, and this avoids multiple walks of virtual bases.  */
20866   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
20867     {
20868       tree r = try_class_unification (tparms, targs, parm,
20869 				      BINFO_TYPE (binfo), explain_p);
20870 
20871       if (r)
20872 	{
20873 	  /* If there is more than one satisfactory baseclass, then:
20874 
20875 	       [temp.deduct.call]
20876 
20877 	      If they yield more than one possible deduced A, the type
20878 	      deduction fails.
20879 
20880 	     applies.  */
20881 	  if (rval && !same_type_p (r, rval))
20882 	    {
20883 	      *result = NULL_TREE;
20884 	      return tbr_ambiguous_baseclass;
20885 	    }
20886 
20887 	  rval = r;
20888 	}
20889     }
20890 
20891   *result = rval;
20892   return tbr_success;
20893 }
20894 
20895 /* Returns the level of DECL, which declares a template parameter.  */
20896 
20897 static int
20898 template_decl_level (tree decl)
20899 {
20900   switch (TREE_CODE (decl))
20901     {
20902     case TYPE_DECL:
20903     case TEMPLATE_DECL:
20904       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
20905 
20906     case PARM_DECL:
20907       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
20908 
20909     default:
20910       gcc_unreachable ();
20911     }
20912   return 0;
20913 }
20914 
20915 /* Decide whether ARG can be unified with PARM, considering only the
20916    cv-qualifiers of each type, given STRICT as documented for unify.
20917    Returns nonzero iff the unification is OK on that basis.  */
20918 
20919 static int
20920 check_cv_quals_for_unify (int strict, tree arg, tree parm)
20921 {
20922   int arg_quals = cp_type_quals (arg);
20923   int parm_quals = cp_type_quals (parm);
20924 
20925   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
20926       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
20927     {
20928       /*  Although a CVR qualifier is ignored when being applied to a
20929 	  substituted template parameter ([8.3.2]/1 for example), that
20930 	  does not allow us to unify "const T" with "int&" because both
20931 	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
20932 	  It is ok when we're allowing additional CV qualifiers
20933 	  at the outer level [14.8.2.1]/3,1st bullet.  */
20934       if ((TREE_CODE (arg) == REFERENCE_TYPE
20935 	   || TREE_CODE (arg) == FUNCTION_TYPE
20936 	   || TREE_CODE (arg) == METHOD_TYPE)
20937 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
20938 	return 0;
20939 
20940       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
20941 	  && (parm_quals & TYPE_QUAL_RESTRICT))
20942 	return 0;
20943     }
20944 
20945   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
20946       && (arg_quals & parm_quals) != parm_quals)
20947     return 0;
20948 
20949   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
20950       && (parm_quals & arg_quals) != arg_quals)
20951     return 0;
20952 
20953   return 1;
20954 }
20955 
20956 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
20957 void
20958 template_parm_level_and_index (tree parm, int* level, int* index)
20959 {
20960   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
20961       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
20962       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20963     {
20964       *index = TEMPLATE_TYPE_IDX (parm);
20965       *level = TEMPLATE_TYPE_LEVEL (parm);
20966     }
20967   else
20968     {
20969       *index = TEMPLATE_PARM_IDX (parm);
20970       *level = TEMPLATE_PARM_LEVEL (parm);
20971     }
20972 }
20973 
20974 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
20975   do {									\
20976     if (unify (TP, TA, P, A, S, EP))					\
20977       return 1;								\
20978   } while (0)
20979 
20980 /* Unifies the remaining arguments in PACKED_ARGS with the pack
20981    expansion at the end of PACKED_PARMS. Returns 0 if the type
20982    deduction succeeds, 1 otherwise. STRICT is the same as in
20983    fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
20984    function call argument list. We'll need to adjust the arguments to make them
20985    types. SUBR tells us if this is from a recursive call to
20986    type_unification_real, or for comparing two template argument
20987    lists. */
20988 
20989 static int
20990 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
20991                       tree packed_args, unification_kind_t strict,
20992                       bool subr, bool explain_p)
20993 {
20994   tree parm
20995     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
20996   tree pattern = PACK_EXPANSION_PATTERN (parm);
20997   tree pack, packs = NULL_TREE;
20998   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
20999 
21000   /* Add in any args remembered from an earlier partial instantiation.  */
21001   targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
21002   int levels = TMPL_ARGS_DEPTH (targs);
21003 
21004   packed_args = expand_template_argument_pack (packed_args);
21005 
21006   int len = TREE_VEC_LENGTH (packed_args);
21007 
21008   /* Determine the parameter packs we will be deducing from the
21009      pattern, and record their current deductions.  */
21010   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
21011        pack; pack = TREE_CHAIN (pack))
21012     {
21013       tree parm_pack = TREE_VALUE (pack);
21014       int idx, level;
21015 
21016       /* Only template parameter packs can be deduced, not e.g. function
21017 	 parameter packs or __bases or __integer_pack.  */
21018       if (!TEMPLATE_PARM_P (parm_pack))
21019 	continue;
21020 
21021       /* Determine the index and level of this parameter pack.  */
21022       template_parm_level_and_index (parm_pack, &level, &idx);
21023       if (level < levels)
21024 	continue;
21025 
21026       /* Keep track of the parameter packs and their corresponding
21027          argument packs.  */
21028       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
21029       TREE_TYPE (packs) = make_tree_vec (len - start);
21030     }
21031 
21032   /* Loop through all of the arguments that have not yet been
21033      unified and unify each with the pattern.  */
21034   for (i = start; i < len; i++)
21035     {
21036       tree parm;
21037       bool any_explicit = false;
21038       tree arg = TREE_VEC_ELT (packed_args, i);
21039 
21040       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
21041 	 or the element of its argument pack at the current index if
21042 	 this argument was explicitly specified.  */
21043       for (pack = packs; pack; pack = TREE_CHAIN (pack))
21044         {
21045           int idx, level;
21046           tree arg, pargs;
21047           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21048 
21049           arg = NULL_TREE;
21050           if (TREE_VALUE (pack)
21051               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
21052               && (i - start < TREE_VEC_LENGTH (pargs)))
21053             {
21054               any_explicit = true;
21055               arg = TREE_VEC_ELT (pargs, i - start);
21056             }
21057           TMPL_ARG (targs, level, idx) = arg;
21058         }
21059 
21060       /* If we had explicit template arguments, substitute them into the
21061 	 pattern before deduction.  */
21062       if (any_explicit)
21063 	{
21064 	  /* Some arguments might still be unspecified or dependent.  */
21065 	  bool dependent;
21066 	  ++processing_template_decl;
21067 	  dependent = any_dependent_template_arguments_p (targs);
21068 	  if (!dependent)
21069 	    --processing_template_decl;
21070 	  parm = tsubst (pattern, targs,
21071 			 explain_p ? tf_warning_or_error : tf_none,
21072 			 NULL_TREE);
21073 	  if (dependent)
21074 	    --processing_template_decl;
21075 	  if (parm == error_mark_node)
21076 	    return 1;
21077 	}
21078       else
21079 	parm = pattern;
21080 
21081       /* Unify the pattern with the current argument.  */
21082       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
21083 			      explain_p))
21084 	return 1;
21085 
21086       /* For each parameter pack, collect the deduced value.  */
21087       for (pack = packs; pack; pack = TREE_CHAIN (pack))
21088         {
21089           int idx, level;
21090           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21091 
21092           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
21093             TMPL_ARG (targs, level, idx);
21094         }
21095     }
21096 
21097   /* Verify that the results of unification with the parameter packs
21098      produce results consistent with what we've seen before, and make
21099      the deduced argument packs available.  */
21100   for (pack = packs; pack; pack = TREE_CHAIN (pack))
21101     {
21102       tree old_pack = TREE_VALUE (pack);
21103       tree new_args = TREE_TYPE (pack);
21104       int i, len = TREE_VEC_LENGTH (new_args);
21105       int idx, level;
21106       bool nondeduced_p = false;
21107 
21108       /* By default keep the original deduced argument pack.
21109 	 If necessary, more specific code is going to update the
21110 	 resulting deduced argument later down in this function.  */
21111       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21112       TMPL_ARG (targs, level, idx) = old_pack;
21113 
21114       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
21115 	 actually deduce anything.  */
21116       for (i = 0; i < len && !nondeduced_p; ++i)
21117 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
21118 	  nondeduced_p = true;
21119       if (nondeduced_p)
21120 	continue;
21121 
21122       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
21123         {
21124           /* If we had fewer function args than explicit template args,
21125              just use the explicits.  */
21126           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
21127           int explicit_len = TREE_VEC_LENGTH (explicit_args);
21128           if (len < explicit_len)
21129             new_args = explicit_args;
21130         }
21131 
21132       if (!old_pack)
21133         {
21134           tree result;
21135           /* Build the deduced *_ARGUMENT_PACK.  */
21136           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
21137             {
21138               result = make_node (NONTYPE_ARGUMENT_PACK);
21139               TREE_CONSTANT (result) = 1;
21140             }
21141           else
21142             result = cxx_make_type (TYPE_ARGUMENT_PACK);
21143 
21144           SET_ARGUMENT_PACK_ARGS (result, new_args);
21145 
21146           /* Note the deduced argument packs for this parameter
21147              pack.  */
21148           TMPL_ARG (targs, level, idx) = result;
21149         }
21150       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
21151                && (ARGUMENT_PACK_ARGS (old_pack)
21152                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
21153         {
21154           /* We only had the explicitly-provided arguments before, but
21155              now we have a complete set of arguments.  */
21156           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
21157 
21158           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
21159           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
21160           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
21161         }
21162       else
21163 	{
21164 	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
21165 	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
21166 
21167 	  if (!comp_template_args (old_args, new_args,
21168 				   &bad_old_arg, &bad_new_arg))
21169 	    /* Inconsistent unification of this parameter pack.  */
21170 	    return unify_parameter_pack_inconsistent (explain_p,
21171 						      bad_old_arg,
21172 						      bad_new_arg);
21173 	}
21174     }
21175 
21176   return unify_success (explain_p);
21177 }
21178 
21179 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
21180    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
21181    parameters and return value are as for unify.  */
21182 
21183 static int
21184 unify_array_domain (tree tparms, tree targs,
21185 		    tree parm_dom, tree arg_dom,
21186 		    bool explain_p)
21187 {
21188   tree parm_max;
21189   tree arg_max;
21190   bool parm_cst;
21191   bool arg_cst;
21192 
21193   /* Our representation of array types uses "N - 1" as the
21194      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
21195      not an integer constant.  We cannot unify arbitrarily
21196      complex expressions, so we eliminate the MINUS_EXPRs
21197      here.  */
21198   parm_max = TYPE_MAX_VALUE (parm_dom);
21199   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
21200   if (!parm_cst)
21201     {
21202       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
21203       parm_max = TREE_OPERAND (parm_max, 0);
21204     }
21205   arg_max = TYPE_MAX_VALUE (arg_dom);
21206   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
21207   if (!arg_cst)
21208     {
21209       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
21210 	 trying to unify the type of a variable with the type
21211 	 of a template parameter.  For example:
21212 
21213 	   template <unsigned int N>
21214 	   void f (char (&) [N]);
21215 	   int g();
21216 	   void h(int i) {
21217 	     char a[g(i)];
21218 	     f(a);
21219 	   }
21220 
21221 	 Here, the type of the ARG will be "int [g(i)]", and
21222 	 may be a SAVE_EXPR, etc.  */
21223       if (TREE_CODE (arg_max) != MINUS_EXPR)
21224 	return unify_vla_arg (explain_p, arg_dom);
21225       arg_max = TREE_OPERAND (arg_max, 0);
21226     }
21227 
21228   /* If only one of the bounds used a MINUS_EXPR, compensate
21229      by adding one to the other bound.  */
21230   if (parm_cst && !arg_cst)
21231     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
21232 				integer_type_node,
21233 				parm_max,
21234 				integer_one_node);
21235   else if (arg_cst && !parm_cst)
21236     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
21237 			       integer_type_node,
21238 			       arg_max,
21239 			       integer_one_node);
21240 
21241   return unify (tparms, targs, parm_max, arg_max,
21242 		UNIFY_ALLOW_INTEGER, explain_p);
21243 }
21244 
21245 /* Returns whether T, a P or A in unify, is a type, template or expression.  */
21246 
21247 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
21248 
21249 static pa_kind_t
21250 pa_kind (tree t)
21251 {
21252   if (PACK_EXPANSION_P (t))
21253     t = PACK_EXPANSION_PATTERN (t);
21254   if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
21255       || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
21256       || DECL_TYPE_TEMPLATE_P (t))
21257     return pa_tmpl;
21258   else if (TYPE_P (t))
21259     return pa_type;
21260   else
21261     return pa_expr;
21262 }
21263 
21264 /* Deduce the value of template parameters.  TPARMS is the (innermost)
21265    set of template parameters to a template.  TARGS is the bindings
21266    for those template parameters, as determined thus far; TARGS may
21267    include template arguments for outer levels of template parameters
21268    as well.  PARM is a parameter to a template function, or a
21269    subcomponent of that parameter; ARG is the corresponding argument.
21270    This function attempts to match PARM with ARG in a manner
21271    consistent with the existing assignments in TARGS.  If more values
21272    are deduced, then TARGS is updated.
21273 
21274    Returns 0 if the type deduction succeeds, 1 otherwise.  The
21275    parameter STRICT is a bitwise or of the following flags:
21276 
21277      UNIFY_ALLOW_NONE:
21278        Require an exact match between PARM and ARG.
21279      UNIFY_ALLOW_MORE_CV_QUAL:
21280        Allow the deduced ARG to be more cv-qualified (by qualification
21281        conversion) than ARG.
21282      UNIFY_ALLOW_LESS_CV_QUAL:
21283        Allow the deduced ARG to be less cv-qualified than ARG.
21284      UNIFY_ALLOW_DERIVED:
21285        Allow the deduced ARG to be a template base class of ARG,
21286        or a pointer to a template base class of the type pointed to by
21287        ARG.
21288      UNIFY_ALLOW_INTEGER:
21289        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
21290        case for more information.
21291      UNIFY_ALLOW_OUTER_LEVEL:
21292        This is the outermost level of a deduction. Used to determine validity
21293        of qualification conversions. A valid qualification conversion must
21294        have const qualified pointers leading up to the inner type which
21295        requires additional CV quals, except at the outer level, where const
21296        is not required [conv.qual]. It would be normal to set this flag in
21297        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
21298      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
21299        This is the outermost level of a deduction, and PARM can be more CV
21300        qualified at this point.
21301      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
21302        This is the outermost level of a deduction, and PARM can be less CV
21303        qualified at this point.  */
21304 
21305 static int
21306 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
21307        bool explain_p)
21308 {
21309   int idx;
21310   tree targ;
21311   tree tparm;
21312   int strict_in = strict;
21313   tsubst_flags_t complain = (explain_p
21314 			     ? tf_warning_or_error
21315 			     : tf_none);
21316 
21317   /* I don't think this will do the right thing with respect to types.
21318      But the only case I've seen it in so far has been array bounds, where
21319      signedness is the only information lost, and I think that will be
21320      okay.  */
21321   while (CONVERT_EXPR_P (parm))
21322     parm = TREE_OPERAND (parm, 0);
21323 
21324   if (arg == error_mark_node)
21325     return unify_invalid (explain_p);
21326   if (arg == unknown_type_node
21327       || arg == init_list_type_node)
21328     /* We can't deduce anything from this, but we might get all the
21329        template args from other function args.  */
21330     return unify_success (explain_p);
21331 
21332   if (parm == any_targ_node || arg == any_targ_node)
21333     return unify_success (explain_p);
21334 
21335   /* If PARM uses template parameters, then we can't bail out here,
21336      even if ARG == PARM, since we won't record unifications for the
21337      template parameters.  We might need them if we're trying to
21338      figure out which of two things is more specialized.  */
21339   if (arg == parm && !uses_template_parms (parm))
21340     return unify_success (explain_p);
21341 
21342   /* Handle init lists early, so the rest of the function can assume
21343      we're dealing with a type. */
21344   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
21345     {
21346       tree elt, elttype;
21347       unsigned i;
21348       tree orig_parm = parm;
21349 
21350       /* Replace T with std::initializer_list<T> for deduction.  */
21351       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21352 	  && flag_deduce_init_list)
21353 	parm = listify (parm);
21354 
21355       if (!is_std_init_list (parm)
21356 	  && TREE_CODE (parm) != ARRAY_TYPE)
21357 	/* We can only deduce from an initializer list argument if the
21358 	   parameter is std::initializer_list or an array; otherwise this
21359 	   is a non-deduced context. */
21360 	return unify_success (explain_p);
21361 
21362       if (TREE_CODE (parm) == ARRAY_TYPE)
21363 	elttype = TREE_TYPE (parm);
21364       else
21365 	{
21366 	  elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
21367 	  /* Deduction is defined in terms of a single type, so just punt
21368 	     on the (bizarre) std::initializer_list<T...>.  */
21369 	  if (PACK_EXPANSION_P (elttype))
21370 	    return unify_success (explain_p);
21371 	}
21372 
21373       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
21374 	{
21375 	  int elt_strict = strict;
21376 
21377 	  if (elt == error_mark_node)
21378 	    return unify_invalid (explain_p);
21379 
21380 	  if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
21381 	    {
21382 	      tree type = TREE_TYPE (elt);
21383 	      if (type == error_mark_node)
21384 		return unify_invalid (explain_p);
21385 	      /* It should only be possible to get here for a call.  */
21386 	      gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
21387 	      elt_strict |= maybe_adjust_types_for_deduction
21388 		(DEDUCE_CALL, &elttype, &type, elt);
21389 	      elt = type;
21390 	    }
21391 
21392 	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
21393 				   explain_p);
21394 	}
21395 
21396       if (TREE_CODE (parm) == ARRAY_TYPE
21397 	  && deducible_array_bound (TYPE_DOMAIN (parm)))
21398 	{
21399 	  /* Also deduce from the length of the initializer list.  */
21400 	  tree max = size_int (CONSTRUCTOR_NELTS (arg));
21401 	  tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
21402 	  if (idx == error_mark_node)
21403 	    return unify_invalid (explain_p);
21404 	  return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
21405 				     idx, explain_p);
21406 	}
21407 
21408       /* If the std::initializer_list<T> deduction worked, replace the
21409 	 deduced A with std::initializer_list<A>.  */
21410       if (orig_parm != parm)
21411 	{
21412 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
21413 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21414 	  targ = listify (targ);
21415 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
21416 	}
21417       return unify_success (explain_p);
21418     }
21419 
21420   /* If parm and arg aren't the same kind of thing (template, type, or
21421      expression), fail early.  */
21422   if (pa_kind (parm) != pa_kind (arg))
21423     return unify_invalid (explain_p);
21424 
21425   /* Immediately reject some pairs that won't unify because of
21426      cv-qualification mismatches.  */
21427   if (TREE_CODE (arg) == TREE_CODE (parm)
21428       && TYPE_P (arg)
21429       /* It is the elements of the array which hold the cv quals of an array
21430 	 type, and the elements might be template type parms. We'll check
21431 	 when we recurse.  */
21432       && TREE_CODE (arg) != ARRAY_TYPE
21433       /* We check the cv-qualifiers when unifying with template type
21434 	 parameters below.  We want to allow ARG `const T' to unify with
21435 	 PARM `T' for example, when computing which of two templates
21436 	 is more specialized, for example.  */
21437       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
21438       && !check_cv_quals_for_unify (strict_in, arg, parm))
21439     return unify_cv_qual_mismatch (explain_p, parm, arg);
21440 
21441   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
21442       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
21443     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
21444   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
21445   strict &= ~UNIFY_ALLOW_DERIVED;
21446   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
21447   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
21448 
21449   switch (TREE_CODE (parm))
21450     {
21451     case TYPENAME_TYPE:
21452     case SCOPE_REF:
21453     case UNBOUND_CLASS_TEMPLATE:
21454       /* In a type which contains a nested-name-specifier, template
21455 	 argument values cannot be deduced for template parameters used
21456 	 within the nested-name-specifier.  */
21457       return unify_success (explain_p);
21458 
21459     case TEMPLATE_TYPE_PARM:
21460     case TEMPLATE_TEMPLATE_PARM:
21461     case BOUND_TEMPLATE_TEMPLATE_PARM:
21462       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
21463       if (error_operand_p (tparm))
21464 	return unify_invalid (explain_p);
21465 
21466       if (TEMPLATE_TYPE_LEVEL (parm)
21467 	  != template_decl_level (tparm))
21468 	/* The PARM is not one we're trying to unify.  Just check
21469 	   to see if it matches ARG.  */
21470 	{
21471 	  if (TREE_CODE (arg) == TREE_CODE (parm)
21472 	      && (is_auto (parm) ? is_auto (arg)
21473 		  : same_type_p (parm, arg)))
21474 	    return unify_success (explain_p);
21475 	  else
21476 	    return unify_type_mismatch (explain_p, parm, arg);
21477 	}
21478       idx = TEMPLATE_TYPE_IDX (parm);
21479       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21480       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
21481       if (error_operand_p (tparm))
21482 	return unify_invalid (explain_p);
21483 
21484       /* Check for mixed types and values.  */
21485       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21486 	   && TREE_CODE (tparm) != TYPE_DECL)
21487 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21488 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
21489 	gcc_unreachable ();
21490 
21491       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21492 	{
21493 	  if ((strict_in & UNIFY_ALLOW_DERIVED)
21494 	      && CLASS_TYPE_P (arg))
21495 	    {
21496 	      /* First try to match ARG directly.  */
21497 	      tree t = try_class_unification (tparms, targs, parm, arg,
21498 					      explain_p);
21499 	      if (!t)
21500 		{
21501 		  /* Otherwise, look for a suitable base of ARG, as below.  */
21502 		  enum template_base_result r;
21503 		  r = get_template_base (tparms, targs, parm, arg,
21504 					 explain_p, &t);
21505 		  if (!t)
21506 		    return unify_no_common_base (explain_p, r, parm, arg);
21507 		  arg = t;
21508 		}
21509 	    }
21510 	  /* ARG must be constructed from a template class or a template
21511 	     template parameter.  */
21512 	  else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
21513 		   && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
21514 	    return unify_template_deduction_failure (explain_p, parm, arg);
21515 
21516 	  /* Deduce arguments T, i from TT<T> or TT<i>.  */
21517 	  if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
21518 	    return 1;
21519 
21520 	  arg = TYPE_TI_TEMPLATE (arg);
21521 
21522 	  /* Fall through to deduce template name.  */
21523 	}
21524 
21525       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21526 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21527 	{
21528 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
21529 
21530 	  /* Simple cases: Value already set, does match or doesn't.  */
21531 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
21532 	    return unify_success (explain_p);
21533 	  else if (targ)
21534 	    return unify_inconsistency (explain_p, parm, targ, arg);
21535 	}
21536       else
21537 	{
21538 	  /* If PARM is `const T' and ARG is only `int', we don't have
21539 	     a match unless we are allowing additional qualification.
21540 	     If ARG is `const int' and PARM is just `T' that's OK;
21541 	     that binds `const int' to `T'.  */
21542 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
21543 					 arg, parm))
21544 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
21545 
21546 	  /* Consider the case where ARG is `const volatile int' and
21547 	     PARM is `const T'.  Then, T should be `volatile int'.  */
21548 	  arg = cp_build_qualified_type_real
21549 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
21550 	  if (arg == error_mark_node)
21551 	    return unify_invalid (explain_p);
21552 
21553 	  /* Simple cases: Value already set, does match or doesn't.  */
21554 	  if (targ != NULL_TREE && same_type_p (targ, arg))
21555 	    return unify_success (explain_p);
21556 	  else if (targ)
21557 	    return unify_inconsistency (explain_p, parm, targ, arg);
21558 
21559 	  /* Make sure that ARG is not a variable-sized array.  (Note
21560 	     that were talking about variable-sized arrays (like
21561 	     `int[n]'), rather than arrays of unknown size (like
21562 	     `int[]').)  We'll get very confused by such a type since
21563 	     the bound of the array is not constant, and therefore
21564 	     not mangleable.  Besides, such types are not allowed in
21565 	     ISO C++, so we can do as we please here.  We do allow
21566 	     them for 'auto' deduction, since that isn't ABI-exposed.  */
21567 	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
21568 	    return unify_vla_arg (explain_p, arg);
21569 
21570 	  /* Strip typedefs as in convert_template_argument.  */
21571 	  arg = canonicalize_type_argument (arg, tf_none);
21572 	}
21573 
21574       /* If ARG is a parameter pack or an expansion, we cannot unify
21575 	 against it unless PARM is also a parameter pack.  */
21576       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
21577 	  && !template_parameter_pack_p (parm))
21578 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
21579 
21580       /* If the argument deduction results is a METHOD_TYPE,
21581          then there is a problem.
21582          METHOD_TYPE doesn't map to any real C++ type the result of
21583 	 the deduction can not be of that type.  */
21584       if (TREE_CODE (arg) == METHOD_TYPE)
21585 	return unify_method_type_error (explain_p, arg);
21586 
21587       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
21588       return unify_success (explain_p);
21589 
21590     case TEMPLATE_PARM_INDEX:
21591       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
21592       if (error_operand_p (tparm))
21593 	return unify_invalid (explain_p);
21594 
21595       if (TEMPLATE_PARM_LEVEL (parm)
21596 	  != template_decl_level (tparm))
21597 	{
21598 	  /* The PARM is not one we're trying to unify.  Just check
21599 	     to see if it matches ARG.  */
21600 	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
21601 			 && cp_tree_equal (parm, arg));
21602 	  if (result)
21603 	    unify_expression_unequal (explain_p, parm, arg);
21604 	  return result;
21605 	}
21606 
21607       idx = TEMPLATE_PARM_IDX (parm);
21608       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21609 
21610       if (targ)
21611 	{
21612 	  if ((strict & UNIFY_ALLOW_INTEGER)
21613 	      && TREE_TYPE (targ) && TREE_TYPE (arg)
21614 	      && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
21615 	    /* We're deducing from an array bound, the type doesn't matter.  */
21616 	    arg = fold_convert (TREE_TYPE (targ), arg);
21617 	  int x = !cp_tree_equal (targ, arg);
21618 	  if (x)
21619 	    unify_inconsistency (explain_p, parm, targ, arg);
21620 	  return x;
21621 	}
21622 
21623       /* [temp.deduct.type] If, in the declaration of a function template
21624 	 with a non-type template-parameter, the non-type
21625 	 template-parameter is used in an expression in the function
21626 	 parameter-list and, if the corresponding template-argument is
21627 	 deduced, the template-argument type shall match the type of the
21628 	 template-parameter exactly, except that a template-argument
21629 	 deduced from an array bound may be of any integral type.
21630 	 The non-type parameter might use already deduced type parameters.  */
21631       tparm = TREE_TYPE (parm);
21632       if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
21633 	/* We don't have enough levels of args to do any substitution.  This
21634 	   can happen in the context of -fnew-ttp-matching.  */;
21635       else
21636 	{
21637 	  ++processing_template_decl;
21638 	  tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
21639 	  --processing_template_decl;
21640 
21641 	  if (tree a = type_uses_auto (tparm))
21642 	    {
21643 	      tparm = do_auto_deduction (tparm, arg, a, complain, adc_unify);
21644 	      if (tparm == error_mark_node)
21645 		return 1;
21646 	    }
21647 	}
21648 
21649       if (!TREE_TYPE (arg))
21650 	/* Template-parameter dependent expression.  Just accept it for now.
21651 	   It will later be processed in convert_template_argument.  */
21652 	;
21653       else if (same_type_p (non_reference (TREE_TYPE (arg)),
21654 			    non_reference (tparm)))
21655 	/* OK */;
21656       else if ((strict & UNIFY_ALLOW_INTEGER)
21657 	       && CP_INTEGRAL_TYPE_P (tparm))
21658 	/* Convert the ARG to the type of PARM; the deduced non-type
21659 	   template argument must exactly match the types of the
21660 	   corresponding parameter.  */
21661 	arg = fold (build_nop (tparm, arg));
21662       else if (uses_template_parms (tparm))
21663 	{
21664 	  /* We haven't deduced the type of this parameter yet.  */
21665 	  if (cxx_dialect >= cxx17
21666 	      /* We deduce from array bounds in try_array_deduction.  */
21667 	      && !(strict & UNIFY_ALLOW_INTEGER))
21668 	    {
21669 	      /* Deduce it from the non-type argument.  */
21670 	      tree atype = TREE_TYPE (arg);
21671 	      RECUR_AND_CHECK_FAILURE (tparms, targs,
21672 				       tparm, atype,
21673 				       UNIFY_ALLOW_NONE, explain_p);
21674 	    }
21675 	  else
21676 	    /* Try again later.  */
21677 	    return unify_success (explain_p);
21678 	}
21679       else
21680 	return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
21681 
21682       /* If ARG is a parameter pack or an expansion, we cannot unify
21683 	 against it unless PARM is also a parameter pack.  */
21684       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
21685 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
21686 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
21687 
21688       {
21689 	bool removed_attr = false;
21690 	arg = strip_typedefs_expr (arg, &removed_attr);
21691       }
21692       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
21693       return unify_success (explain_p);
21694 
21695     case PTRMEM_CST:
21696      {
21697 	/* A pointer-to-member constant can be unified only with
21698 	 another constant.  */
21699       if (TREE_CODE (arg) != PTRMEM_CST)
21700 	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
21701 
21702       /* Just unify the class member. It would be useless (and possibly
21703 	 wrong, depending on the strict flags) to unify also
21704 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
21705 	 arg refer to the same variable, even if through different
21706 	 classes. For instance:
21707 
21708 	 struct A { int x; };
21709 	 struct B : A { };
21710 
21711 	 Unification of &A::x and &B::x must succeed.  */
21712       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
21713 		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
21714      }
21715 
21716     case POINTER_TYPE:
21717       {
21718 	if (!TYPE_PTR_P (arg))
21719 	  return unify_type_mismatch (explain_p, parm, arg);
21720 
21721 	/* [temp.deduct.call]
21722 
21723 	   A can be another pointer or pointer to member type that can
21724 	   be converted to the deduced A via a qualification
21725 	   conversion (_conv.qual_).
21726 
21727 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
21728 	   This will allow for additional cv-qualification of the
21729 	   pointed-to types if appropriate.  */
21730 
21731 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
21732 	  /* The derived-to-base conversion only persists through one
21733 	     level of pointers.  */
21734 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
21735 
21736 	return unify (tparms, targs, TREE_TYPE (parm),
21737 		      TREE_TYPE (arg), strict, explain_p);
21738       }
21739 
21740     case REFERENCE_TYPE:
21741       if (TREE_CODE (arg) != REFERENCE_TYPE)
21742 	return unify_type_mismatch (explain_p, parm, arg);
21743       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21744 		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
21745 
21746     case ARRAY_TYPE:
21747       if (TREE_CODE (arg) != ARRAY_TYPE)
21748 	return unify_type_mismatch (explain_p, parm, arg);
21749       if ((TYPE_DOMAIN (parm) == NULL_TREE)
21750 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
21751 	return unify_type_mismatch (explain_p, parm, arg);
21752       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21753 			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
21754       if (TYPE_DOMAIN (parm) != NULL_TREE)
21755 	return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
21756 				   TYPE_DOMAIN (arg), explain_p);
21757       return unify_success (explain_p);
21758 
21759     case REAL_TYPE:
21760     case COMPLEX_TYPE:
21761     case VECTOR_TYPE:
21762     case INTEGER_TYPE:
21763     case BOOLEAN_TYPE:
21764     case ENUMERAL_TYPE:
21765     case VOID_TYPE:
21766     case NULLPTR_TYPE:
21767       if (TREE_CODE (arg) != TREE_CODE (parm))
21768 	return unify_type_mismatch (explain_p, parm, arg);
21769 
21770       /* We have already checked cv-qualification at the top of the
21771 	 function.  */
21772       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
21773 	return unify_type_mismatch (explain_p, parm, arg);
21774 
21775       /* As far as unification is concerned, this wins.	 Later checks
21776 	 will invalidate it if necessary.  */
21777       return unify_success (explain_p);
21778 
21779       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
21780       /* Type INTEGER_CST can come from ordinary constant template args.  */
21781     case INTEGER_CST:
21782       while (CONVERT_EXPR_P (arg))
21783 	arg = TREE_OPERAND (arg, 0);
21784 
21785       if (TREE_CODE (arg) != INTEGER_CST)
21786 	return unify_template_argument_mismatch (explain_p, parm, arg);
21787       return (tree_int_cst_equal (parm, arg)
21788 	      ? unify_success (explain_p)
21789 	      : unify_template_argument_mismatch (explain_p, parm, arg));
21790 
21791     case TREE_VEC:
21792       {
21793 	int i, len, argslen;
21794 	int parm_variadic_p = 0;
21795 
21796 	if (TREE_CODE (arg) != TREE_VEC)
21797 	  return unify_template_argument_mismatch (explain_p, parm, arg);
21798 
21799 	len = TREE_VEC_LENGTH (parm);
21800 	argslen = TREE_VEC_LENGTH (arg);
21801 
21802 	/* Check for pack expansions in the parameters.  */
21803 	for (i = 0; i < len; ++i)
21804 	  {
21805 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
21806 	      {
21807 		if (i == len - 1)
21808 		  /* We can unify against something with a trailing
21809 		     parameter pack.  */
21810 		  parm_variadic_p = 1;
21811 		else
21812 		  /* [temp.deduct.type]/9: If the template argument list of
21813 		     P contains a pack expansion that is not the last
21814 		     template argument, the entire template argument list
21815 		     is a non-deduced context.  */
21816 		  return unify_success (explain_p);
21817 	      }
21818 	  }
21819 
21820         /* If we don't have enough arguments to satisfy the parameters
21821            (not counting the pack expression at the end), or we have
21822            too many arguments for a parameter list that doesn't end in
21823            a pack expression, we can't unify.  */
21824 	if (parm_variadic_p
21825 	    ? argslen < len - parm_variadic_p
21826 	    : argslen != len)
21827 	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
21828 
21829 	/* Unify all of the parameters that precede the (optional)
21830 	   pack expression.  */
21831 	for (i = 0; i < len - parm_variadic_p; ++i)
21832 	  {
21833 	    RECUR_AND_CHECK_FAILURE (tparms, targs,
21834 				     TREE_VEC_ELT (parm, i),
21835 				     TREE_VEC_ELT (arg, i),
21836 				     UNIFY_ALLOW_NONE, explain_p);
21837 	  }
21838 	if (parm_variadic_p)
21839 	  return unify_pack_expansion (tparms, targs, parm, arg,
21840 				       DEDUCE_EXACT,
21841 				       /*subr=*/true, explain_p);
21842 	return unify_success (explain_p);
21843       }
21844 
21845     case RECORD_TYPE:
21846     case UNION_TYPE:
21847       if (TREE_CODE (arg) != TREE_CODE (parm))
21848 	return unify_type_mismatch (explain_p, parm, arg);
21849 
21850       if (TYPE_PTRMEMFUNC_P (parm))
21851 	{
21852 	  if (!TYPE_PTRMEMFUNC_P (arg))
21853 	    return unify_type_mismatch (explain_p, parm, arg);
21854 
21855 	  return unify (tparms, targs,
21856 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
21857 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
21858 			strict, explain_p);
21859 	}
21860       else if (TYPE_PTRMEMFUNC_P (arg))
21861 	return unify_type_mismatch (explain_p, parm, arg);
21862 
21863       if (CLASSTYPE_TEMPLATE_INFO (parm))
21864 	{
21865 	  tree t = NULL_TREE;
21866 
21867 	  if (strict_in & UNIFY_ALLOW_DERIVED)
21868 	    {
21869 	      /* First, we try to unify the PARM and ARG directly.  */
21870 	      t = try_class_unification (tparms, targs,
21871 					 parm, arg, explain_p);
21872 
21873 	      if (!t)
21874 		{
21875 		  /* Fallback to the special case allowed in
21876 		     [temp.deduct.call]:
21877 
21878 		       If P is a class, and P has the form
21879 		       template-id, then A can be a derived class of
21880 		       the deduced A.  Likewise, if P is a pointer to
21881 		       a class of the form template-id, A can be a
21882 		       pointer to a derived class pointed to by the
21883 		       deduced A.  */
21884 		  enum template_base_result r;
21885 		  r = get_template_base (tparms, targs, parm, arg,
21886 					 explain_p, &t);
21887 
21888 		  if (!t)
21889 		    {
21890 		      /* Don't give the derived diagnostic if we're
21891 			 already dealing with the same template.  */
21892 		      bool same_template
21893 			= (CLASSTYPE_TEMPLATE_INFO (arg)
21894 			   && (CLASSTYPE_TI_TEMPLATE (parm)
21895 			       == CLASSTYPE_TI_TEMPLATE (arg)));
21896 		      return unify_no_common_base (explain_p && !same_template,
21897 						   r, parm, arg);
21898 		    }
21899 		}
21900 	    }
21901 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
21902 		   && (CLASSTYPE_TI_TEMPLATE (parm)
21903 		       == CLASSTYPE_TI_TEMPLATE (arg)))
21904 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
21905 	       Then, we should unify `int' and `U'.  */
21906 	    t = arg;
21907 	  else
21908 	    /* There's no chance of unification succeeding.  */
21909 	    return unify_type_mismatch (explain_p, parm, arg);
21910 
21911 	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
21912 			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
21913 	}
21914       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
21915 	return unify_type_mismatch (explain_p, parm, arg);
21916       return unify_success (explain_p);
21917 
21918     case METHOD_TYPE:
21919     case FUNCTION_TYPE:
21920       {
21921 	unsigned int nargs;
21922 	tree *args;
21923 	tree a;
21924 	unsigned int i;
21925 
21926 	if (TREE_CODE (arg) != TREE_CODE (parm))
21927 	  return unify_type_mismatch (explain_p, parm, arg);
21928 
21929 	/* CV qualifications for methods can never be deduced, they must
21930 	   match exactly.  We need to check them explicitly here,
21931 	   because type_unification_real treats them as any other
21932 	   cv-qualified parameter.  */
21933 	if (TREE_CODE (parm) == METHOD_TYPE
21934 	    && (!check_cv_quals_for_unify
21935 		(UNIFY_ALLOW_NONE,
21936 		 class_of_this_parm (arg),
21937 		 class_of_this_parm (parm))))
21938 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
21939 	if (TREE_CODE (arg) == FUNCTION_TYPE
21940 	    && type_memfn_quals (parm) != type_memfn_quals (arg))
21941 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
21942 	if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
21943 	  return unify_type_mismatch (explain_p, parm, arg);
21944 
21945 	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
21946 				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
21947 
21948 	nargs = list_length (TYPE_ARG_TYPES (arg));
21949 	args = XALLOCAVEC (tree, nargs);
21950 	for (a = TYPE_ARG_TYPES (arg), i = 0;
21951 	     a != NULL_TREE && a != void_list_node;
21952 	     a = TREE_CHAIN (a), ++i)
21953 	  args[i] = TREE_VALUE (a);
21954 	nargs = i;
21955 
21956 	if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
21957 				   args, nargs, 1, DEDUCE_EXACT,
21958 				   LOOKUP_NORMAL, NULL, explain_p))
21959 	  return 1;
21960 
21961 	if (flag_noexcept_type)
21962 	  {
21963 	    tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
21964 	    tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
21965 	    if (pspec == NULL_TREE) pspec = noexcept_false_spec;
21966 	    if (aspec == NULL_TREE) aspec = noexcept_false_spec;
21967 	    if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
21968 		&& uses_template_parms (TREE_PURPOSE (pspec)))
21969 	      RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
21970 				       TREE_PURPOSE (aspec),
21971 				       UNIFY_ALLOW_NONE, explain_p);
21972 	    else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
21973 	      return unify_type_mismatch (explain_p, parm, arg);
21974 	  }
21975 
21976 	return 0;
21977       }
21978 
21979     case OFFSET_TYPE:
21980       /* Unify a pointer to member with a pointer to member function, which
21981 	 deduces the type of the member as a function type. */
21982       if (TYPE_PTRMEMFUNC_P (arg))
21983 	{
21984 	  /* Check top-level cv qualifiers */
21985 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
21986 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
21987 
21988 	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
21989 				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
21990 				   UNIFY_ALLOW_NONE, explain_p);
21991 
21992 	  /* Determine the type of the function we are unifying against. */
21993 	  tree fntype = static_fn_type (arg);
21994 
21995 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
21996 	}
21997 
21998       if (TREE_CODE (arg) != OFFSET_TYPE)
21999 	return unify_type_mismatch (explain_p, parm, arg);
22000       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
22001 			       TYPE_OFFSET_BASETYPE (arg),
22002 			       UNIFY_ALLOW_NONE, explain_p);
22003       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
22004 		    strict, explain_p);
22005 
22006     case CONST_DECL:
22007       if (DECL_TEMPLATE_PARM_P (parm))
22008 	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
22009       if (arg != scalar_constant_value (parm))
22010 	return unify_template_argument_mismatch (explain_p, parm, arg);
22011       return unify_success (explain_p);
22012 
22013     case FIELD_DECL:
22014     case TEMPLATE_DECL:
22015       /* Matched cases are handled by the ARG == PARM test above.  */
22016       return unify_template_argument_mismatch (explain_p, parm, arg);
22017 
22018     case VAR_DECL:
22019       /* We might get a variable as a non-type template argument in parm if the
22020 	 corresponding parameter is type-dependent.  Make any necessary
22021 	 adjustments based on whether arg is a reference.  */
22022       if (CONSTANT_CLASS_P (arg))
22023 	parm = fold_non_dependent_expr (parm);
22024       else if (REFERENCE_REF_P (arg))
22025 	{
22026 	  tree sub = TREE_OPERAND (arg, 0);
22027 	  STRIP_NOPS (sub);
22028 	  if (TREE_CODE (sub) == ADDR_EXPR)
22029 	    arg = TREE_OPERAND (sub, 0);
22030 	}
22031       /* Now use the normal expression code to check whether they match.  */
22032       goto expr;
22033 
22034     case TYPE_ARGUMENT_PACK:
22035     case NONTYPE_ARGUMENT_PACK:
22036       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
22037 		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
22038 
22039     case TYPEOF_TYPE:
22040     case DECLTYPE_TYPE:
22041     case UNDERLYING_TYPE:
22042       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
22043 	 or UNDERLYING_TYPE nodes.  */
22044       return unify_success (explain_p);
22045 
22046     case ERROR_MARK:
22047       /* Unification fails if we hit an error node.  */
22048       return unify_invalid (explain_p);
22049 
22050     case INDIRECT_REF:
22051       if (REFERENCE_REF_P (parm))
22052 	{
22053 	  bool pexp = PACK_EXPANSION_P (arg);
22054 	  if (pexp)
22055 	    arg = PACK_EXPANSION_PATTERN (arg);
22056 	  if (REFERENCE_REF_P (arg))
22057 	    arg = TREE_OPERAND (arg, 0);
22058 	  if (pexp)
22059 	    arg = make_pack_expansion (arg, complain);
22060 	  return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
22061 			strict, explain_p);
22062 	}
22063       /* FALLTHRU */
22064 
22065     default:
22066       /* An unresolved overload is a nondeduced context.  */
22067       if (is_overloaded_fn (parm) || type_unknown_p (parm))
22068 	return unify_success (explain_p);
22069       gcc_assert (EXPR_P (parm) || TREE_CODE (parm) == TRAIT_EXPR);
22070     expr:
22071       /* We must be looking at an expression.  This can happen with
22072 	 something like:
22073 
22074 	   template <int I>
22075 	   void foo(S<I>, S<I + 2>);
22076 
22077 	 This is a "nondeduced context":
22078 
22079 	   [deduct.type]
22080 
22081 	   The nondeduced contexts are:
22082 
22083 	   --A type that is a template-id in which one or more of
22084 	     the template-arguments is an expression that references
22085 	     a template-parameter.
22086 
22087 	 In these cases, we assume deduction succeeded, but don't
22088 	 actually infer any unifications.  */
22089 
22090       if (!uses_template_parms (parm)
22091 	  && !template_args_equal (parm, arg))
22092 	return unify_expression_unequal (explain_p, parm, arg);
22093       else
22094 	return unify_success (explain_p);
22095     }
22096 }
22097 #undef RECUR_AND_CHECK_FAILURE
22098 
22099 /* Note that DECL can be defined in this translation unit, if
22100    required.  */
22101 
22102 static void
22103 mark_definable (tree decl)
22104 {
22105   tree clone;
22106   DECL_NOT_REALLY_EXTERN (decl) = 1;
22107   FOR_EACH_CLONE (clone, decl)
22108     DECL_NOT_REALLY_EXTERN (clone) = 1;
22109 }
22110 
22111 /* Called if RESULT is explicitly instantiated, or is a member of an
22112    explicitly instantiated class.  */
22113 
22114 void
22115 mark_decl_instantiated (tree result, int extern_p)
22116 {
22117   SET_DECL_EXPLICIT_INSTANTIATION (result);
22118 
22119   /* If this entity has already been written out, it's too late to
22120      make any modifications.  */
22121   if (TREE_ASM_WRITTEN (result))
22122     return;
22123 
22124   /* For anonymous namespace we don't need to do anything.  */
22125   if (decl_anon_ns_mem_p (result))
22126     {
22127       gcc_assert (!TREE_PUBLIC (result));
22128       return;
22129     }
22130 
22131   if (TREE_CODE (result) != FUNCTION_DECL)
22132     /* The TREE_PUBLIC flag for function declarations will have been
22133        set correctly by tsubst.  */
22134     TREE_PUBLIC (result) = 1;
22135 
22136   /* This might have been set by an earlier implicit instantiation.  */
22137   DECL_COMDAT (result) = 0;
22138 
22139   if (extern_p)
22140     DECL_NOT_REALLY_EXTERN (result) = 0;
22141   else
22142     {
22143       mark_definable (result);
22144       mark_needed (result);
22145       /* Always make artificials weak.  */
22146       if (DECL_ARTIFICIAL (result) && flag_weak)
22147 	comdat_linkage (result);
22148       /* For WIN32 we also want to put explicit instantiations in
22149 	 linkonce sections.  */
22150       else if (TREE_PUBLIC (result))
22151 	maybe_make_one_only (result);
22152     }
22153 
22154   /* If EXTERN_P, then this function will not be emitted -- unless
22155      followed by an explicit instantiation, at which point its linkage
22156      will be adjusted.  If !EXTERN_P, then this function will be
22157      emitted here.  In neither circumstance do we want
22158      import_export_decl to adjust the linkage.  */
22159   DECL_INTERFACE_KNOWN (result) = 1;
22160 }
22161 
22162 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
22163    important template arguments.  If any are missing, we check whether
22164    they're important by using error_mark_node for substituting into any
22165    args that were used for partial ordering (the ones between ARGS and END)
22166    and seeing if it bubbles up.  */
22167 
22168 static bool
22169 check_undeduced_parms (tree targs, tree args, tree end)
22170 {
22171   bool found = false;
22172   int i;
22173   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
22174     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
22175       {
22176 	found = true;
22177 	TREE_VEC_ELT (targs, i) = error_mark_node;
22178       }
22179   if (found)
22180     {
22181       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
22182       if (substed == error_mark_node)
22183 	return true;
22184     }
22185   return false;
22186 }
22187 
22188 /* Given two function templates PAT1 and PAT2, return:
22189 
22190    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
22191    -1 if PAT2 is more specialized than PAT1.
22192    0 if neither is more specialized.
22193 
22194    LEN indicates the number of parameters we should consider
22195    (defaulted parameters should not be considered).
22196 
22197    The 1998 std underspecified function template partial ordering, and
22198    DR214 addresses the issue.  We take pairs of arguments, one from
22199    each of the templates, and deduce them against each other.  One of
22200    the templates will be more specialized if all the *other*
22201    template's arguments deduce against its arguments and at least one
22202    of its arguments *does* *not* deduce against the other template's
22203    corresponding argument.  Deduction is done as for class templates.
22204    The arguments used in deduction have reference and top level cv
22205    qualifiers removed.  Iff both arguments were originally reference
22206    types *and* deduction succeeds in both directions, an lvalue reference
22207    wins against an rvalue reference and otherwise the template
22208    with the more cv-qualified argument wins for that pairing (if
22209    neither is more cv-qualified, they both are equal).  Unlike regular
22210    deduction, after all the arguments have been deduced in this way,
22211    we do *not* verify the deduced template argument values can be
22212    substituted into non-deduced contexts.
22213 
22214    The logic can be a bit confusing here, because we look at deduce1 and
22215    targs1 to see if pat2 is at least as specialized, and vice versa; if we
22216    can find template arguments for pat1 to make arg1 look like arg2, that
22217    means that arg2 is at least as specialized as arg1.  */
22218 
22219 int
22220 more_specialized_fn (tree pat1, tree pat2, int len)
22221 {
22222   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
22223   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
22224   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
22225   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
22226   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
22227   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
22228   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
22229   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
22230   tree origs1, origs2;
22231   bool lose1 = false;
22232   bool lose2 = false;
22233 
22234   /* Remove the this parameter from non-static member functions.  If
22235      one is a non-static member function and the other is not a static
22236      member function, remove the first parameter from that function
22237      also.  This situation occurs for operator functions where we
22238      locate both a member function (with this pointer) and non-member
22239      operator (with explicit first operand).  */
22240   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
22241     {
22242       len--; /* LEN is the number of significant arguments for DECL1 */
22243       args1 = TREE_CHAIN (args1);
22244       if (!DECL_STATIC_FUNCTION_P (decl2))
22245 	args2 = TREE_CHAIN (args2);
22246     }
22247   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
22248     {
22249       args2 = TREE_CHAIN (args2);
22250       if (!DECL_STATIC_FUNCTION_P (decl1))
22251 	{
22252 	  len--;
22253 	  args1 = TREE_CHAIN (args1);
22254 	}
22255     }
22256 
22257   /* If only one is a conversion operator, they are unordered.  */
22258   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
22259     return 0;
22260 
22261   /* Consider the return type for a conversion function */
22262   if (DECL_CONV_FN_P (decl1))
22263     {
22264       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
22265       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
22266       len++;
22267     }
22268 
22269   processing_template_decl++;
22270 
22271   origs1 = args1;
22272   origs2 = args2;
22273 
22274   while (len--
22275 	 /* Stop when an ellipsis is seen.  */
22276 	 && args1 != NULL_TREE && args2 != NULL_TREE)
22277     {
22278       tree arg1 = TREE_VALUE (args1);
22279       tree arg2 = TREE_VALUE (args2);
22280       int deduce1, deduce2;
22281       int quals1 = -1;
22282       int quals2 = -1;
22283       int ref1 = 0;
22284       int ref2 = 0;
22285 
22286       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
22287           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22288         {
22289           /* When both arguments are pack expansions, we need only
22290              unify the patterns themselves.  */
22291           arg1 = PACK_EXPANSION_PATTERN (arg1);
22292           arg2 = PACK_EXPANSION_PATTERN (arg2);
22293 
22294           /* This is the last comparison we need to do.  */
22295           len = 0;
22296         }
22297 
22298       /* DR 1847: If a particular P contains no template-parameters that
22299 	 participate in template argument deduction, that P is not used to
22300 	 determine the ordering.  */
22301       if (!uses_deducible_template_parms (arg1)
22302 	  && !uses_deducible_template_parms (arg2))
22303 	goto next;
22304 
22305       if (TREE_CODE (arg1) == REFERENCE_TYPE)
22306 	{
22307 	  ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
22308 	  arg1 = TREE_TYPE (arg1);
22309 	  quals1 = cp_type_quals (arg1);
22310 	}
22311 
22312       if (TREE_CODE (arg2) == REFERENCE_TYPE)
22313 	{
22314 	  ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
22315 	  arg2 = TREE_TYPE (arg2);
22316 	  quals2 = cp_type_quals (arg2);
22317 	}
22318 
22319       arg1 = TYPE_MAIN_VARIANT (arg1);
22320       arg2 = TYPE_MAIN_VARIANT (arg2);
22321 
22322       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
22323         {
22324           int i, len2 = remaining_arguments (args2);
22325           tree parmvec = make_tree_vec (1);
22326           tree argvec = make_tree_vec (len2);
22327           tree ta = args2;
22328 
22329           /* Setup the parameter vector, which contains only ARG1.  */
22330           TREE_VEC_ELT (parmvec, 0) = arg1;
22331 
22332           /* Setup the argument vector, which contains the remaining
22333              arguments.  */
22334           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
22335             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
22336 
22337           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
22338 					   argvec, DEDUCE_EXACT,
22339 					   /*subr=*/true, /*explain_p=*/false)
22340 		     == 0);
22341 
22342           /* We cannot deduce in the other direction, because ARG1 is
22343              a pack expansion but ARG2 is not.  */
22344           deduce2 = 0;
22345         }
22346       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22347         {
22348           int i, len1 = remaining_arguments (args1);
22349           tree parmvec = make_tree_vec (1);
22350           tree argvec = make_tree_vec (len1);
22351           tree ta = args1;
22352 
22353           /* Setup the parameter vector, which contains only ARG1.  */
22354           TREE_VEC_ELT (parmvec, 0) = arg2;
22355 
22356           /* Setup the argument vector, which contains the remaining
22357              arguments.  */
22358           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
22359             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
22360 
22361           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
22362 					   argvec, DEDUCE_EXACT,
22363 					   /*subr=*/true, /*explain_p=*/false)
22364 		     == 0);
22365 
22366           /* We cannot deduce in the other direction, because ARG2 is
22367              a pack expansion but ARG1 is not.*/
22368           deduce1 = 0;
22369         }
22370 
22371       else
22372         {
22373           /* The normal case, where neither argument is a pack
22374              expansion.  */
22375           deduce1 = (unify (tparms1, targs1, arg1, arg2,
22376 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
22377 		     == 0);
22378           deduce2 = (unify (tparms2, targs2, arg2, arg1,
22379 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
22380 		     == 0);
22381         }
22382 
22383       /* If we couldn't deduce arguments for tparms1 to make arg1 match
22384 	 arg2, then arg2 is not as specialized as arg1.  */
22385       if (!deduce1)
22386 	lose2 = true;
22387       if (!deduce2)
22388 	lose1 = true;
22389 
22390       /* "If, for a given type, deduction succeeds in both directions
22391 	 (i.e., the types are identical after the transformations above)
22392 	 and both P and A were reference types (before being replaced with
22393 	 the type referred to above):
22394 	 - if the type from the argument template was an lvalue reference and
22395 	 the type from the parameter template was not, the argument type is
22396 	 considered to be more specialized than the other; otherwise,
22397 	 - if the type from the argument template is more cv-qualified
22398 	 than the type from the parameter template (as described above),
22399 	 the argument type is considered to be more specialized than the other;
22400 	 otherwise,
22401 	 - neither type is more specialized than the other."  */
22402 
22403       if (deduce1 && deduce2)
22404 	{
22405 	  if (ref1 && ref2 && ref1 != ref2)
22406 	    {
22407 	      if (ref1 > ref2)
22408 		lose1 = true;
22409 	      else
22410 		lose2 = true;
22411 	    }
22412 	  else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
22413 	    {
22414 	      if ((quals1 & quals2) == quals2)
22415 		lose2 = true;
22416 	      if ((quals1 & quals2) == quals1)
22417 		lose1 = true;
22418 	    }
22419 	}
22420 
22421       if (lose1 && lose2)
22422 	/* We've failed to deduce something in either direction.
22423 	   These must be unordered.  */
22424 	break;
22425 
22426     next:
22427 
22428       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
22429           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22430         /* We have already processed all of the arguments in our
22431            handing of the pack expansion type.  */
22432         len = 0;
22433 
22434       args1 = TREE_CHAIN (args1);
22435       args2 = TREE_CHAIN (args2);
22436     }
22437 
22438   /* "In most cases, all template parameters must have values in order for
22439      deduction to succeed, but for partial ordering purposes a template
22440      parameter may remain without a value provided it is not used in the
22441      types being used for partial ordering."
22442 
22443      Thus, if we are missing any of the targs1 we need to substitute into
22444      origs1, then pat2 is not as specialized as pat1.  This can happen when
22445      there is a nondeduced context.  */
22446   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
22447     lose2 = true;
22448   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
22449     lose1 = true;
22450 
22451   processing_template_decl--;
22452 
22453   /* If both deductions succeed, the partial ordering selects the more
22454      constrained template.  */
22455   if (!lose1 && !lose2)
22456     {
22457       tree c1 = get_constraints (DECL_TEMPLATE_RESULT (pat1));
22458       tree c2 = get_constraints (DECL_TEMPLATE_RESULT (pat2));
22459       lose1 = !subsumes_constraints (c1, c2);
22460       lose2 = !subsumes_constraints (c2, c1);
22461     }
22462 
22463   /* All things being equal, if the next argument is a pack expansion
22464      for one function but not for the other, prefer the
22465      non-variadic function.  FIXME this is bogus; see c++/41958.  */
22466   if (lose1 == lose2
22467       && args1 && TREE_VALUE (args1)
22468       && args2 && TREE_VALUE (args2))
22469     {
22470       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
22471       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
22472     }
22473 
22474   if (lose1 == lose2)
22475     return 0;
22476   else if (!lose1)
22477     return 1;
22478   else
22479     return -1;
22480 }
22481 
22482 /* Determine which of two partial specializations of TMPL is more
22483    specialized.
22484 
22485    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
22486    to the first partial specialization.  The TREE_PURPOSE is the
22487    innermost set of template parameters for the partial
22488    specialization.  PAT2 is similar, but for the second template.
22489 
22490    Return 1 if the first partial specialization is more specialized;
22491    -1 if the second is more specialized; 0 if neither is more
22492    specialized.
22493 
22494    See [temp.class.order] for information about determining which of
22495    two templates is more specialized.  */
22496 
22497 static int
22498 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
22499 {
22500   tree targs;
22501   int winner = 0;
22502   bool any_deductions = false;
22503 
22504   tree tmpl1 = TREE_VALUE (pat1);
22505   tree tmpl2 = TREE_VALUE (pat2);
22506   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
22507   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
22508 
22509   /* Just like what happens for functions, if we are ordering between
22510      different template specializations, we may encounter dependent
22511      types in the arguments, and we need our dependency check functions
22512      to behave correctly.  */
22513   ++processing_template_decl;
22514   targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
22515   if (targs)
22516     {
22517       --winner;
22518       any_deductions = true;
22519     }
22520 
22521   targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
22522   if (targs)
22523     {
22524       ++winner;
22525       any_deductions = true;
22526     }
22527   --processing_template_decl;
22528 
22529   /* If both deductions succeed, the partial ordering selects the more
22530      constrained template.  */
22531   if (!winner && any_deductions)
22532     return more_constrained (tmpl1, tmpl2);
22533 
22534   /* In the case of a tie where at least one of the templates
22535      has a parameter pack at the end, the template with the most
22536      non-packed parameters wins.  */
22537   if (winner == 0
22538       && any_deductions
22539       && (template_args_variadic_p (TREE_PURPOSE (pat1))
22540           || template_args_variadic_p (TREE_PURPOSE (pat2))))
22541     {
22542       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
22543       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
22544       int len1 = TREE_VEC_LENGTH (args1);
22545       int len2 = TREE_VEC_LENGTH (args2);
22546 
22547       /* We don't count the pack expansion at the end.  */
22548       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
22549         --len1;
22550       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
22551         --len2;
22552 
22553       if (len1 > len2)
22554         return 1;
22555       else if (len1 < len2)
22556         return -1;
22557     }
22558 
22559   return winner;
22560 }
22561 
22562 /* Return the template arguments that will produce the function signature
22563    DECL from the function template FN, with the explicit template
22564    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
22565    also match.  Return NULL_TREE if no satisfactory arguments could be
22566    found.  */
22567 
22568 static tree
22569 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
22570 {
22571   int ntparms = DECL_NTPARMS (fn);
22572   tree targs = make_tree_vec (ntparms);
22573   tree decl_type = TREE_TYPE (decl);
22574   tree decl_arg_types;
22575   tree *args;
22576   unsigned int nargs, ix;
22577   tree arg;
22578 
22579   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
22580 
22581   /* Never do unification on the 'this' parameter.  */
22582   decl_arg_types = skip_artificial_parms_for (decl,
22583 					      TYPE_ARG_TYPES (decl_type));
22584 
22585   nargs = list_length (decl_arg_types);
22586   args = XALLOCAVEC (tree, nargs);
22587   for (arg = decl_arg_types, ix = 0;
22588        arg != NULL_TREE && arg != void_list_node;
22589        arg = TREE_CHAIN (arg), ++ix)
22590     args[ix] = TREE_VALUE (arg);
22591 
22592   if (fn_type_unification (fn, explicit_args, targs,
22593 			   args, ix,
22594 			   (check_rettype || DECL_CONV_FN_P (fn)
22595 			    ? TREE_TYPE (decl_type) : NULL_TREE),
22596 			   DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false,
22597 			   /*decltype*/false)
22598       == error_mark_node)
22599     return NULL_TREE;
22600 
22601   return targs;
22602 }
22603 
22604 /* Return the innermost template arguments that, when applied to a partial
22605    specialization SPEC_TMPL of TMPL, yield the ARGS.
22606 
22607    For example, suppose we have:
22608 
22609      template <class T, class U> struct S {};
22610      template <class T> struct S<T*, int> {};
22611 
22612    Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
22613    partial specialization and the ARGS will be {double*, int}.  The resulting
22614    vector will be {double}, indicating that `T' is bound to `double'.  */
22615 
22616 static tree
22617 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
22618 {
22619   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
22620   tree spec_args
22621     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
22622   int i, ntparms = TREE_VEC_LENGTH (tparms);
22623   tree deduced_args;
22624   tree innermost_deduced_args;
22625 
22626   innermost_deduced_args = make_tree_vec (ntparms);
22627   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
22628     {
22629       deduced_args = copy_node (args);
22630       SET_TMPL_ARGS_LEVEL (deduced_args,
22631 			   TMPL_ARGS_DEPTH (deduced_args),
22632 			   innermost_deduced_args);
22633     }
22634   else
22635     deduced_args = innermost_deduced_args;
22636 
22637   bool tried_array_deduction = (cxx_dialect < cxx17);
22638  again:
22639   if (unify (tparms, deduced_args,
22640 	     INNERMOST_TEMPLATE_ARGS (spec_args),
22641 	     INNERMOST_TEMPLATE_ARGS (args),
22642 	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
22643     return NULL_TREE;
22644 
22645   for (i =  0; i < ntparms; ++i)
22646     if (! TREE_VEC_ELT (innermost_deduced_args, i))
22647       {
22648 	if (!tried_array_deduction)
22649 	  {
22650 	    try_array_deduction (tparms, innermost_deduced_args,
22651 				 INNERMOST_TEMPLATE_ARGS (spec_args));
22652 	    tried_array_deduction = true;
22653 	    if (TREE_VEC_ELT (innermost_deduced_args, i))
22654 	      goto again;
22655 	  }
22656 	return NULL_TREE;
22657       }
22658 
22659   if (!push_tinst_level (spec_tmpl, deduced_args))
22660     {
22661       excessive_deduction_depth = true;
22662       return NULL_TREE;
22663     }
22664 
22665   /* Verify that nondeduced template arguments agree with the type
22666      obtained from argument deduction.
22667 
22668      For example:
22669 
22670        struct A { typedef int X; };
22671        template <class T, class U> struct C {};
22672        template <class T> struct C<T, typename T::X> {};
22673 
22674      Then with the instantiation `C<A, int>', we can deduce that
22675      `T' is `A' but unify () does not check whether `typename T::X'
22676      is `int'.  */
22677   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
22678 
22679   if (spec_args != error_mark_node)
22680     spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
22681 				       INNERMOST_TEMPLATE_ARGS (spec_args),
22682 				       tmpl, tf_none, false, false);
22683 
22684   pop_tinst_level ();
22685 
22686   if (spec_args == error_mark_node
22687       /* We only need to check the innermost arguments; the other
22688 	 arguments will always agree.  */
22689       || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
22690 				     INNERMOST_TEMPLATE_ARGS (args)))
22691     return NULL_TREE;
22692 
22693   /* Now that we have bindings for all of the template arguments,
22694      ensure that the arguments deduced for the template template
22695      parameters have compatible template parameter lists.  See the use
22696      of template_template_parm_bindings_ok_p in fn_type_unification
22697      for more information.  */
22698   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
22699     return NULL_TREE;
22700 
22701   return deduced_args;
22702 }
22703 
22704 // Compare two function templates T1 and T2 by deducing bindings
22705 // from one against the other. If both deductions succeed, compare
22706 // constraints to see which is more constrained.
22707 static int
22708 more_specialized_inst (tree t1, tree t2)
22709 {
22710   int fate = 0;
22711   int count = 0;
22712 
22713   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
22714     {
22715       --fate;
22716       ++count;
22717     }
22718 
22719   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
22720     {
22721       ++fate;
22722       ++count;
22723     }
22724 
22725   // If both deductions succeed, then one may be more constrained.
22726   if (count == 2 && fate == 0)
22727     fate = more_constrained (t1, t2);
22728 
22729   return fate;
22730 }
22731 
22732 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
22733    Return the TREE_LIST node with the most specialized template, if
22734    any.  If there is no most specialized template, the error_mark_node
22735    is returned.
22736 
22737    Note that this function does not look at, or modify, the
22738    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
22739    returned is one of the elements of INSTANTIATIONS, callers may
22740    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
22741    and retrieve it from the value returned.  */
22742 
22743 tree
22744 most_specialized_instantiation (tree templates)
22745 {
22746   tree fn, champ;
22747 
22748   ++processing_template_decl;
22749 
22750   champ = templates;
22751   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
22752     {
22753       gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
22754       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
22755       if (fate == -1)
22756 	champ = fn;
22757       else if (!fate)
22758 	{
22759 	  /* Equally specialized, move to next function.  If there
22760 	     is no next function, nothing's most specialized.  */
22761 	  fn = TREE_CHAIN (fn);
22762 	  champ = fn;
22763 	  if (!fn)
22764 	    break;
22765 	}
22766     }
22767 
22768   if (champ)
22769     /* Now verify that champ is better than everything earlier in the
22770        instantiation list.  */
22771     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
22772       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
22773       {
22774         champ = NULL_TREE;
22775         break;
22776       }
22777     }
22778 
22779   processing_template_decl--;
22780 
22781   if (!champ)
22782     return error_mark_node;
22783 
22784   return champ;
22785 }
22786 
22787 /* If DECL is a specialization of some template, return the most
22788    general such template.  Otherwise, returns NULL_TREE.
22789 
22790    For example, given:
22791 
22792      template <class T> struct S { template <class U> void f(U); };
22793 
22794    if TMPL is `template <class U> void S<int>::f(U)' this will return
22795    the full template.  This function will not trace past partial
22796    specializations, however.  For example, given in addition:
22797 
22798      template <class T> struct S<T*> { template <class U> void f(U); };
22799 
22800    if TMPL is `template <class U> void S<int*>::f(U)' this will return
22801    `template <class T> template <class U> S<T*>::f(U)'.  */
22802 
22803 tree
22804 most_general_template (tree decl)
22805 {
22806   if (TREE_CODE (decl) != TEMPLATE_DECL)
22807     {
22808       if (tree tinfo = get_template_info (decl))
22809 	decl = TI_TEMPLATE (tinfo);
22810       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
22811 	 template friend, or a FIELD_DECL for a capture pack.  */
22812       if (TREE_CODE (decl) != TEMPLATE_DECL)
22813 	return NULL_TREE;
22814     }
22815 
22816   /* Look for more and more general templates.  */
22817   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
22818     {
22819       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
22820 	 (See cp-tree.h for details.)  */
22821       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
22822 	break;
22823 
22824       if (CLASS_TYPE_P (TREE_TYPE (decl))
22825 	  && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
22826 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
22827 	break;
22828 
22829       /* Stop if we run into an explicitly specialized class template.  */
22830       if (!DECL_NAMESPACE_SCOPE_P (decl)
22831 	  && DECL_CONTEXT (decl)
22832 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
22833 	break;
22834 
22835       decl = DECL_TI_TEMPLATE (decl);
22836     }
22837 
22838   return decl;
22839 }
22840 
22841 /* Return the most specialized of the template partial specializations
22842    which can produce TARGET, a specialization of some class or variable
22843    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
22844    a TEMPLATE_DECL node corresponding to the partial specialization, while
22845    the TREE_PURPOSE is the set of template arguments that must be
22846    substituted into the template pattern in order to generate TARGET.
22847 
22848    If the choice of partial specialization is ambiguous, a diagnostic
22849    is issued, and the error_mark_node is returned.  If there are no
22850    partial specializations matching TARGET, then NULL_TREE is
22851    returned, indicating that the primary template should be used.  */
22852 
22853 static tree
22854 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
22855 {
22856   tree list = NULL_TREE;
22857   tree t;
22858   tree champ;
22859   int fate;
22860   bool ambiguous_p;
22861   tree outer_args = NULL_TREE;
22862   tree tmpl, args;
22863 
22864   if (TYPE_P (target))
22865     {
22866       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
22867       tmpl = TI_TEMPLATE (tinfo);
22868       args = TI_ARGS (tinfo);
22869     }
22870   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
22871     {
22872       tmpl = TREE_OPERAND (target, 0);
22873       args = TREE_OPERAND (target, 1);
22874     }
22875   else if (VAR_P (target))
22876     {
22877       tree tinfo = DECL_TEMPLATE_INFO (target);
22878       tmpl = TI_TEMPLATE (tinfo);
22879       args = TI_ARGS (tinfo);
22880     }
22881   else
22882     gcc_unreachable ();
22883 
22884   tree main_tmpl = most_general_template (tmpl);
22885 
22886   /* For determining which partial specialization to use, only the
22887      innermost args are interesting.  */
22888   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
22889     {
22890       outer_args = strip_innermost_template_args (args, 1);
22891       args = INNERMOST_TEMPLATE_ARGS (args);
22892     }
22893 
22894   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
22895     {
22896       tree spec_args;
22897       tree spec_tmpl = TREE_VALUE (t);
22898 
22899       if (outer_args)
22900 	{
22901 	  /* Substitute in the template args from the enclosing class.  */
22902 	  ++processing_template_decl;
22903 	  spec_tmpl = tsubst (spec_tmpl, outer_args, tf_none, NULL_TREE);
22904 	  --processing_template_decl;
22905 	}
22906 
22907       if (spec_tmpl == error_mark_node)
22908 	return error_mark_node;
22909 
22910       spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
22911       if (spec_args)
22912 	{
22913 	  if (outer_args)
22914 	    spec_args = add_to_template_args (outer_args, spec_args);
22915 
22916           /* Keep the candidate only if the constraints are satisfied,
22917              or if we're not compiling with concepts.  */
22918           if (!flag_concepts
22919               || constraints_satisfied_p (spec_tmpl, spec_args))
22920             {
22921               list = tree_cons (spec_args, TREE_VALUE (t), list);
22922               TREE_TYPE (list) = TREE_TYPE (t);
22923             }
22924 	}
22925     }
22926 
22927   if (! list)
22928     return NULL_TREE;
22929 
22930   ambiguous_p = false;
22931   t = list;
22932   champ = t;
22933   t = TREE_CHAIN (t);
22934   for (; t; t = TREE_CHAIN (t))
22935     {
22936       fate = more_specialized_partial_spec (tmpl, champ, t);
22937       if (fate == 1)
22938 	;
22939       else
22940 	{
22941 	  if (fate == 0)
22942 	    {
22943 	      t = TREE_CHAIN (t);
22944 	      if (! t)
22945 		{
22946 		  ambiguous_p = true;
22947 		  break;
22948 		}
22949 	    }
22950 	  champ = t;
22951 	}
22952     }
22953 
22954   if (!ambiguous_p)
22955     for (t = list; t && t != champ; t = TREE_CHAIN (t))
22956       {
22957 	fate = more_specialized_partial_spec (tmpl, champ, t);
22958 	if (fate != 1)
22959 	  {
22960 	    ambiguous_p = true;
22961 	    break;
22962 	  }
22963       }
22964 
22965   if (ambiguous_p)
22966     {
22967       const char *str;
22968       char *spaces = NULL;
22969       if (!(complain & tf_error))
22970 	return error_mark_node;
22971       if (TYPE_P (target))
22972 	error ("ambiguous template instantiation for %q#T", target);
22973       else
22974 	error ("ambiguous template instantiation for %q#D", target);
22975       str = ngettext ("candidate is:", "candidates are:", list_length (list));
22976       for (t = list; t; t = TREE_CHAIN (t))
22977         {
22978 	  tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
22979           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
22980 		  "%s %#qS", spaces ? spaces : str, subst);
22981           spaces = spaces ? spaces : get_spaces (str);
22982         }
22983       free (spaces);
22984       return error_mark_node;
22985     }
22986 
22987   return champ;
22988 }
22989 
22990 /* Explicitly instantiate DECL.  */
22991 
22992 void
22993 do_decl_instantiation (tree decl, tree storage)
22994 {
22995   tree result = NULL_TREE;
22996   int extern_p = 0;
22997 
22998   if (!decl || decl == error_mark_node)
22999     /* An error occurred, for which grokdeclarator has already issued
23000        an appropriate message.  */
23001     return;
23002   else if (! DECL_LANG_SPECIFIC (decl))
23003     {
23004       error ("explicit instantiation of non-template %q#D", decl);
23005       return;
23006     }
23007 
23008   bool var_templ = (DECL_TEMPLATE_INFO (decl)
23009                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
23010 
23011   if (VAR_P (decl) && !var_templ)
23012     {
23013       /* There is an asymmetry here in the way VAR_DECLs and
23014 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
23015 	 the latter, the DECL we get back will be marked as a
23016 	 template instantiation, and the appropriate
23017 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
23018 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
23019 	 should handle VAR_DECLs as it currently handles
23020 	 FUNCTION_DECLs.  */
23021       if (!DECL_CLASS_SCOPE_P (decl))
23022 	{
23023 	  error ("%qD is not a static data member of a class template", decl);
23024 	  return;
23025 	}
23026       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
23027       if (!result || !VAR_P (result))
23028 	{
23029 	  error ("no matching template for %qD found", decl);
23030 	  return;
23031 	}
23032       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
23033 	{
23034 	  error ("type %qT for explicit instantiation %qD does not match "
23035 		 "declared type %qT", TREE_TYPE (result), decl,
23036 		 TREE_TYPE (decl));
23037 	  return;
23038 	}
23039     }
23040   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
23041     {
23042       error ("explicit instantiation of %q#D", decl);
23043       return;
23044     }
23045   else
23046     result = decl;
23047 
23048   /* Check for various error cases.  Note that if the explicit
23049      instantiation is valid the RESULT will currently be marked as an
23050      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
23051      until we get here.  */
23052 
23053   if (DECL_TEMPLATE_SPECIALIZATION (result))
23054     {
23055       /* DR 259 [temp.spec].
23056 
23057 	 Both an explicit instantiation and a declaration of an explicit
23058 	 specialization shall not appear in a program unless the explicit
23059 	 instantiation follows a declaration of the explicit specialization.
23060 
23061 	 For a given set of template parameters, if an explicit
23062 	 instantiation of a template appears after a declaration of an
23063 	 explicit specialization for that template, the explicit
23064 	 instantiation has no effect.  */
23065       return;
23066     }
23067   else if (DECL_EXPLICIT_INSTANTIATION (result))
23068     {
23069       /* [temp.spec]
23070 
23071 	 No program shall explicitly instantiate any template more
23072 	 than once.
23073 
23074 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
23075 	 the first instantiation was `extern' and the second is not,
23076 	 and EXTERN_P for the opposite case.  */
23077       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
23078 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
23079       /* If an "extern" explicit instantiation follows an ordinary
23080 	 explicit instantiation, the template is instantiated.  */
23081       if (extern_p)
23082 	return;
23083     }
23084   else if (!DECL_IMPLICIT_INSTANTIATION (result))
23085     {
23086       error ("no matching template for %qD found", result);
23087       return;
23088     }
23089   else if (!DECL_TEMPLATE_INFO (result))
23090     {
23091       permerror (input_location, "explicit instantiation of non-template %q#D", result);
23092       return;
23093     }
23094 
23095   if (storage == NULL_TREE)
23096     ;
23097   else if (storage == ridpointers[(int) RID_EXTERN])
23098     {
23099       if (!in_system_header_at (input_location) && (cxx_dialect == cxx98))
23100 	pedwarn (input_location, OPT_Wpedantic,
23101 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
23102 		 "instantiations");
23103       extern_p = 1;
23104     }
23105   else
23106     error ("storage class %qD applied to template instantiation", storage);
23107 
23108   check_explicit_instantiation_namespace (result);
23109   mark_decl_instantiated (result, extern_p);
23110   if (! extern_p)
23111     instantiate_decl (result, /*defer_ok=*/true,
23112 		      /*expl_inst_class_mem_p=*/false);
23113 }
23114 
23115 static void
23116 mark_class_instantiated (tree t, int extern_p)
23117 {
23118   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
23119   SET_CLASSTYPE_INTERFACE_KNOWN (t);
23120   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
23121   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
23122   if (! extern_p)
23123     {
23124       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
23125       rest_of_type_compilation (t, 1);
23126     }
23127 }
23128 
23129 /* Called from do_type_instantiation through binding_table_foreach to
23130    do recursive instantiation for the type bound in ENTRY.  */
23131 static void
23132 bt_instantiate_type_proc (binding_entry entry, void *data)
23133 {
23134   tree storage = *(tree *) data;
23135 
23136   if (MAYBE_CLASS_TYPE_P (entry->type)
23137       && CLASSTYPE_TEMPLATE_INFO (entry->type)
23138       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
23139     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
23140 }
23141 
23142 /* Perform an explicit instantiation of template class T.  STORAGE, if
23143    non-null, is the RID for extern, inline or static.  COMPLAIN is
23144    nonzero if this is called from the parser, zero if called recursively,
23145    since the standard is unclear (as detailed below).  */
23146 
23147 void
23148 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
23149 {
23150   int extern_p = 0;
23151   int nomem_p = 0;
23152   int static_p = 0;
23153   int previous_instantiation_extern_p = 0;
23154 
23155   if (TREE_CODE (t) == TYPE_DECL)
23156     t = TREE_TYPE (t);
23157 
23158   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
23159     {
23160       tree tmpl =
23161 	(TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
23162       if (tmpl)
23163 	error ("explicit instantiation of non-class template %qD", tmpl);
23164       else
23165 	error ("explicit instantiation of non-template type %qT", t);
23166       return;
23167     }
23168 
23169   complete_type (t);
23170 
23171   if (!COMPLETE_TYPE_P (t))
23172     {
23173       if (complain & tf_error)
23174 	error ("explicit instantiation of %q#T before definition of template",
23175 	       t);
23176       return;
23177     }
23178 
23179   if (storage != NULL_TREE)
23180     {
23181       if (!in_system_header_at (input_location))
23182 	{
23183 	  if (storage == ridpointers[(int) RID_EXTERN])
23184 	    {
23185 	      if (cxx_dialect == cxx98)
23186 		pedwarn (input_location, OPT_Wpedantic,
23187 			 "ISO C++ 1998 forbids the use of %<extern%> on "
23188 			 "explicit instantiations");
23189 	    }
23190 	  else
23191 	    pedwarn (input_location, OPT_Wpedantic,
23192 		     "ISO C++ forbids the use of %qE"
23193 		     " on explicit instantiations", storage);
23194 	}
23195 
23196       if (storage == ridpointers[(int) RID_INLINE])
23197 	nomem_p = 1;
23198       else if (storage == ridpointers[(int) RID_EXTERN])
23199 	extern_p = 1;
23200       else if (storage == ridpointers[(int) RID_STATIC])
23201 	static_p = 1;
23202       else
23203 	{
23204 	  error ("storage class %qD applied to template instantiation",
23205 		 storage);
23206 	  extern_p = 0;
23207 	}
23208     }
23209 
23210   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
23211     {
23212       /* DR 259 [temp.spec].
23213 
23214 	 Both an explicit instantiation and a declaration of an explicit
23215 	 specialization shall not appear in a program unless the explicit
23216 	 instantiation follows a declaration of the explicit specialization.
23217 
23218 	 For a given set of template parameters, if an explicit
23219 	 instantiation of a template appears after a declaration of an
23220 	 explicit specialization for that template, the explicit
23221 	 instantiation has no effect.  */
23222       return;
23223     }
23224   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
23225     {
23226       /* [temp.spec]
23227 
23228 	 No program shall explicitly instantiate any template more
23229 	 than once.
23230 
23231 	 If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
23232 	 instantiation was `extern'.  If EXTERN_P then the second is.
23233 	 These cases are OK.  */
23234       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
23235 
23236       if (!previous_instantiation_extern_p && !extern_p
23237 	  && (complain & tf_error))
23238 	permerror (input_location, "duplicate explicit instantiation of %q#T", t);
23239 
23240       /* If we've already instantiated the template, just return now.  */
23241       if (!CLASSTYPE_INTERFACE_ONLY (t))
23242 	return;
23243     }
23244 
23245   check_explicit_instantiation_namespace (TYPE_NAME (t));
23246   mark_class_instantiated (t, extern_p);
23247 
23248   if (nomem_p)
23249     return;
23250 
23251   /* In contrast to implicit instantiation, where only the
23252      declarations, and not the definitions, of members are
23253      instantiated, we have here:
23254 
23255 	 [temp.explicit]
23256 
23257 	 The explicit instantiation of a class template specialization
23258 	 implies the instantiation of all of its members not
23259 	 previously explicitly specialized in the translation unit
23260 	 containing the explicit instantiation.
23261 
23262      Of course, we can't instantiate member template classes, since we
23263      don't have any arguments for them.  Note that the standard is
23264      unclear on whether the instantiation of the members are
23265      *explicit* instantiations or not.  However, the most natural
23266      interpretation is that it should be an explicit
23267      instantiation.  */
23268   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
23269     if ((VAR_P (fld)
23270 	 || (TREE_CODE (fld) == FUNCTION_DECL
23271 	     && !static_p
23272 	     && user_provided_p (fld)))
23273 	&& DECL_TEMPLATE_INSTANTIATION (fld))
23274       {
23275 	mark_decl_instantiated (fld, extern_p);
23276 	if (! extern_p)
23277 	  instantiate_decl (fld, /*defer_ok=*/true,
23278 			    /*expl_inst_class_mem_p=*/true);
23279       }
23280 
23281   if (CLASSTYPE_NESTED_UTDS (t))
23282     binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
23283 			   bt_instantiate_type_proc, &storage);
23284 }
23285 
23286 /* Given a function DECL, which is a specialization of TMPL, modify
23287    DECL to be a re-instantiation of TMPL with the same template
23288    arguments.  TMPL should be the template into which tsubst'ing
23289    should occur for DECL, not the most general template.
23290 
23291    One reason for doing this is a scenario like this:
23292 
23293      template <class T>
23294      void f(const T&, int i);
23295 
23296      void g() { f(3, 7); }
23297 
23298      template <class T>
23299      void f(const T& t, const int i) { }
23300 
23301    Note that when the template is first instantiated, with
23302    instantiate_template, the resulting DECL will have no name for the
23303    first parameter, and the wrong type for the second.  So, when we go
23304    to instantiate the DECL, we regenerate it.  */
23305 
23306 static void
23307 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
23308 {
23309   /* The arguments used to instantiate DECL, from the most general
23310      template.  */
23311   tree code_pattern;
23312 
23313   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
23314 
23315   /* Make sure that we can see identifiers, and compute access
23316      correctly.  */
23317   push_access_scope (decl);
23318 
23319   if (TREE_CODE (decl) == FUNCTION_DECL)
23320     {
23321       tree decl_parm;
23322       tree pattern_parm;
23323       tree specs;
23324       int args_depth;
23325       int parms_depth;
23326 
23327       args_depth = TMPL_ARGS_DEPTH (args);
23328       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
23329       if (args_depth > parms_depth)
23330 	args = get_innermost_template_args (args, parms_depth);
23331 
23332       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
23333 					      args, tf_error, NULL_TREE,
23334 					      /*defer_ok*/false);
23335       if (specs && specs != error_mark_node)
23336 	TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
23337 						    specs);
23338 
23339       /* Merge parameter declarations.  */
23340       decl_parm = skip_artificial_parms_for (decl,
23341 					     DECL_ARGUMENTS (decl));
23342       pattern_parm
23343 	= skip_artificial_parms_for (code_pattern,
23344 				     DECL_ARGUMENTS (code_pattern));
23345       while (decl_parm && !DECL_PACK_P (pattern_parm))
23346 	{
23347 	  tree parm_type;
23348 	  tree attributes;
23349 
23350 	  if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
23351 	    DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
23352 	  parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
23353 			      NULL_TREE);
23354 	  parm_type = type_decays_to (parm_type);
23355 	  if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
23356 	    TREE_TYPE (decl_parm) = parm_type;
23357 	  attributes = DECL_ATTRIBUTES (pattern_parm);
23358 	  if (DECL_ATTRIBUTES (decl_parm) != attributes)
23359 	    {
23360 	      DECL_ATTRIBUTES (decl_parm) = attributes;
23361 	      cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
23362 	    }
23363 	  decl_parm = DECL_CHAIN (decl_parm);
23364 	  pattern_parm = DECL_CHAIN (pattern_parm);
23365 	}
23366       /* Merge any parameters that match with the function parameter
23367          pack.  */
23368       if (pattern_parm && DECL_PACK_P (pattern_parm))
23369         {
23370           int i, len;
23371           tree expanded_types;
23372           /* Expand the TYPE_PACK_EXPANSION that provides the types for
23373              the parameters in this function parameter pack.  */
23374           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
23375                                                  args, tf_error, NULL_TREE);
23376           len = TREE_VEC_LENGTH (expanded_types);
23377           for (i = 0; i < len; i++)
23378             {
23379               tree parm_type;
23380               tree attributes;
23381 
23382               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
23383                 /* Rename the parameter to include the index.  */
23384                 DECL_NAME (decl_parm) =
23385                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
23386               parm_type = TREE_VEC_ELT (expanded_types, i);
23387               parm_type = type_decays_to (parm_type);
23388               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
23389                 TREE_TYPE (decl_parm) = parm_type;
23390               attributes = DECL_ATTRIBUTES (pattern_parm);
23391               if (DECL_ATTRIBUTES (decl_parm) != attributes)
23392                 {
23393                   DECL_ATTRIBUTES (decl_parm) = attributes;
23394                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
23395                 }
23396               decl_parm = DECL_CHAIN (decl_parm);
23397             }
23398         }
23399       /* Merge additional specifiers from the CODE_PATTERN.  */
23400       if (DECL_DECLARED_INLINE_P (code_pattern)
23401 	  && !DECL_DECLARED_INLINE_P (decl))
23402 	DECL_DECLARED_INLINE_P (decl) = 1;
23403     }
23404   else if (VAR_P (decl))
23405     {
23406       start_lambda_scope (decl);
23407       DECL_INITIAL (decl) =
23408 	tsubst_expr (DECL_INITIAL (code_pattern), args,
23409 		     tf_error, DECL_TI_TEMPLATE (decl),
23410 		     /*integral_constant_expression_p=*/false);
23411       finish_lambda_scope ();
23412       if (VAR_HAD_UNKNOWN_BOUND (decl))
23413 	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
23414 				   tf_error, DECL_TI_TEMPLATE (decl));
23415     }
23416   else
23417     gcc_unreachable ();
23418 
23419   pop_access_scope (decl);
23420 }
23421 
23422 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
23423    substituted to get DECL.  */
23424 
23425 tree
23426 template_for_substitution (tree decl)
23427 {
23428   tree tmpl = DECL_TI_TEMPLATE (decl);
23429 
23430   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
23431      for the instantiation.  This is not always the most general
23432      template.  Consider, for example:
23433 
23434 	template <class T>
23435 	struct S { template <class U> void f();
23436 		   template <> void f<int>(); };
23437 
23438      and an instantiation of S<double>::f<int>.  We want TD to be the
23439      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
23440   while (/* An instantiation cannot have a definition, so we need a
23441 	    more general template.  */
23442 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
23443 	   /* We must also deal with friend templates.  Given:
23444 
23445 		template <class T> struct S {
23446 		  template <class U> friend void f() {};
23447 		};
23448 
23449 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
23450 	      so far as the language is concerned, but that's still
23451 	      where we get the pattern for the instantiation from.  On
23452 	      other hand, if the definition comes outside the class, say:
23453 
23454 		template <class T> struct S {
23455 		  template <class U> friend void f();
23456 		};
23457 		template <class U> friend void f() {}
23458 
23459 	      we don't need to look any further.  That's what the check for
23460 	      DECL_INITIAL is for.  */
23461 	  || (TREE_CODE (decl) == FUNCTION_DECL
23462 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
23463 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
23464     {
23465       /* The present template, TD, should not be a definition.  If it
23466 	 were a definition, we should be using it!  Note that we
23467 	 cannot restructure the loop to just keep going until we find
23468 	 a template with a definition, since that might go too far if
23469 	 a specialization was declared, but not defined.  */
23470 
23471       /* Fetch the more general template.  */
23472       tmpl = DECL_TI_TEMPLATE (tmpl);
23473     }
23474 
23475   return tmpl;
23476 }
23477 
23478 /* Returns true if we need to instantiate this template instance even if we
23479    know we aren't going to emit it.  */
23480 
23481 bool
23482 always_instantiate_p (tree decl)
23483 {
23484   /* We always instantiate inline functions so that we can inline them.  An
23485      explicit instantiation declaration prohibits implicit instantiation of
23486      non-inline functions.  With high levels of optimization, we would
23487      normally inline non-inline functions -- but we're not allowed to do
23488      that for "extern template" functions.  Therefore, we check
23489      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
23490   return ((TREE_CODE (decl) == FUNCTION_DECL
23491 	   && (DECL_DECLARED_INLINE_P (decl)
23492 	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
23493 	  /* And we need to instantiate static data members so that
23494 	     their initializers are available in integral constant
23495 	     expressions.  */
23496 	  || (VAR_P (decl)
23497 	      && decl_maybe_constant_var_p (decl)));
23498 }
23499 
23500 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
23501    instantiate it now, modifying TREE_TYPE (fn).  Returns false on
23502    error, true otherwise.  */
23503 
23504 bool
23505 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
23506 {
23507   tree fntype, spec, noex, clone;
23508 
23509   /* Don't instantiate a noexcept-specification from template context.  */
23510   if (processing_template_decl
23511       && (!flag_noexcept_type || type_dependent_expression_p (fn)))
23512     return true;
23513 
23514   if (DECL_CLONED_FUNCTION_P (fn))
23515     fn = DECL_CLONED_FUNCTION (fn);
23516   fntype = TREE_TYPE (fn);
23517   spec = TYPE_RAISES_EXCEPTIONS (fntype);
23518 
23519   if (!spec || !TREE_PURPOSE (spec))
23520     return true;
23521 
23522   noex = TREE_PURPOSE (spec);
23523 
23524   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
23525     {
23526       static hash_set<tree>* fns = new hash_set<tree>;
23527       bool added = false;
23528       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
23529 	spec = get_defaulted_eh_spec (fn, complain);
23530       else if (!(added = !fns->add (fn)))
23531 	{
23532 	  /* If hash_set::add returns true, the element was already there.  */
23533 	  location_t loc = EXPR_LOC_OR_LOC (DEFERRED_NOEXCEPT_PATTERN (noex),
23534 					    DECL_SOURCE_LOCATION (fn));
23535 	  error_at (loc,
23536 		    "exception specification of %qD depends on itself",
23537 		    fn);
23538 	  spec = noexcept_false_spec;
23539 	}
23540       else if (push_tinst_level (fn))
23541 	{
23542 	  push_access_scope (fn);
23543 	  push_deferring_access_checks (dk_no_deferred);
23544 	  input_location = DECL_SOURCE_LOCATION (fn);
23545 	  noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
23546 					DEFERRED_NOEXCEPT_ARGS (noex),
23547 					tf_warning_or_error, fn,
23548 					/*function_p=*/false,
23549 					/*integral_constant_expression_p=*/true);
23550 	  spec = build_noexcept_spec (noex, tf_warning_or_error);
23551 	  pop_deferring_access_checks ();
23552 	  pop_access_scope (fn);
23553 	  pop_tinst_level ();
23554 	  if (spec == error_mark_node)
23555 	    spec = noexcept_false_spec;
23556 	}
23557       else
23558 	spec = noexcept_false_spec;
23559 
23560       if (added)
23561 	fns->remove (fn);
23562 
23563       if (spec == error_mark_node)
23564 	return false;
23565 
23566       TREE_TYPE (fn) = build_exception_variant (fntype, spec);
23567     }
23568 
23569   FOR_EACH_CLONE (clone, fn)
23570     {
23571       if (TREE_TYPE (clone) == fntype)
23572 	TREE_TYPE (clone) = TREE_TYPE (fn);
23573       else
23574 	TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
23575     }
23576 
23577   return true;
23578 }
23579 
23580 /* We're starting to process the function INST, an instantiation of PATTERN;
23581    add their parameters to local_specializations.  */
23582 
23583 static void
23584 register_parameter_specializations (tree pattern, tree inst)
23585 {
23586   tree tmpl_parm = DECL_ARGUMENTS (pattern);
23587   tree spec_parm = DECL_ARGUMENTS (inst);
23588   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
23589     {
23590       register_local_specialization (spec_parm, tmpl_parm);
23591       spec_parm = skip_artificial_parms_for (inst, spec_parm);
23592       tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
23593     }
23594   for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
23595     {
23596       if (!DECL_PACK_P (tmpl_parm))
23597 	{
23598 	  register_local_specialization (spec_parm, tmpl_parm);
23599 	  spec_parm = DECL_CHAIN (spec_parm);
23600 	}
23601       else
23602 	{
23603 	  /* Register the (value) argument pack as a specialization of
23604 	     TMPL_PARM, then move on.  */
23605 	  tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
23606 	  register_local_specialization (argpack, tmpl_parm);
23607 	}
23608     }
23609   gcc_assert (!spec_parm);
23610 }
23611 
23612 /* Produce the definition of D, a _DECL generated from a template.  If
23613    DEFER_OK is true, then we don't have to actually do the
23614    instantiation now; we just have to do it sometime.  Normally it is
23615    an error if this is an explicit instantiation but D is undefined.
23616    EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
23617    instantiated class template.  */
23618 
23619 tree
23620 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
23621 {
23622   tree tmpl = DECL_TI_TEMPLATE (d);
23623   tree gen_args;
23624   tree args;
23625   tree td;
23626   tree code_pattern;
23627   tree spec;
23628   tree gen_tmpl;
23629   bool pattern_defined;
23630   location_t saved_loc = input_location;
23631   int saved_unevaluated_operand = cp_unevaluated_operand;
23632   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
23633   bool external_p;
23634   bool deleted_p;
23635 
23636   /* This function should only be used to instantiate templates for
23637      functions and static member variables.  */
23638   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
23639 
23640   /* A concept is never instantiated. */
23641   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
23642 
23643   /* Variables are never deferred; if instantiation is required, they
23644      are instantiated right away.  That allows for better code in the
23645      case that an expression refers to the value of the variable --
23646      if the variable has a constant value the referring expression can
23647      take advantage of that fact.  */
23648   if (VAR_P (d))
23649     defer_ok = false;
23650 
23651   /* Don't instantiate cloned functions.  Instead, instantiate the
23652      functions they cloned.  */
23653   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
23654     d = DECL_CLONED_FUNCTION (d);
23655 
23656   if (DECL_TEMPLATE_INSTANTIATED (d)
23657       || (TREE_CODE (d) == FUNCTION_DECL
23658 	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
23659       || DECL_TEMPLATE_SPECIALIZATION (d))
23660     /* D has already been instantiated or explicitly specialized, so
23661        there's nothing for us to do here.
23662 
23663        It might seem reasonable to check whether or not D is an explicit
23664        instantiation, and, if so, stop here.  But when an explicit
23665        instantiation is deferred until the end of the compilation,
23666        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
23667        the instantiation.  */
23668     return d;
23669 
23670   /* Check to see whether we know that this template will be
23671      instantiated in some other file, as with "extern template"
23672      extension.  */
23673   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
23674 
23675   /* In general, we do not instantiate such templates.  */
23676   if (external_p && !always_instantiate_p (d))
23677     return d;
23678 
23679   gen_tmpl = most_general_template (tmpl);
23680   gen_args = DECL_TI_ARGS (d);
23681 
23682   if (tmpl != gen_tmpl)
23683     /* We should already have the extra args.  */
23684     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
23685 		== TMPL_ARGS_DEPTH (gen_args));
23686   /* And what's in the hash table should match D.  */
23687   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
23688 	      || spec == NULL_TREE);
23689 
23690   /* This needs to happen before any tsubsting.  */
23691   if (! push_tinst_level (d))
23692     return d;
23693 
23694   timevar_push (TV_TEMPLATE_INST);
23695 
23696   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
23697      for the instantiation.  */
23698   td = template_for_substitution (d);
23699   args = gen_args;
23700 
23701   if (VAR_P (d))
23702     {
23703       /* Look up an explicit specialization, if any.  */
23704       tree tid = lookup_template_variable (gen_tmpl, gen_args);
23705       tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
23706       if (elt && elt != error_mark_node)
23707 	{
23708 	  td = TREE_VALUE (elt);
23709 	  args = TREE_PURPOSE (elt);
23710 	}
23711     }
23712 
23713   code_pattern = DECL_TEMPLATE_RESULT (td);
23714 
23715   /* We should never be trying to instantiate a member of a class
23716      template or partial specialization.  */
23717   gcc_assert (d != code_pattern);
23718 
23719   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
23720       || DECL_TEMPLATE_SPECIALIZATION (td))
23721     /* In the case of a friend template whose definition is provided
23722        outside the class, we may have too many arguments.  Drop the
23723        ones we don't need.  The same is true for specializations.  */
23724     args = get_innermost_template_args
23725       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
23726 
23727   if (TREE_CODE (d) == FUNCTION_DECL)
23728     {
23729       deleted_p = DECL_DELETED_FN (code_pattern);
23730       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
23731 			  && DECL_INITIAL (code_pattern) != error_mark_node)
23732 			 || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern)
23733 			 || deleted_p);
23734     }
23735   else
23736     {
23737       deleted_p = false;
23738       if (DECL_CLASS_SCOPE_P (code_pattern))
23739 	pattern_defined = (! DECL_IN_AGGR_P (code_pattern)
23740 			   || DECL_INLINE_VAR_P (code_pattern));
23741       else
23742 	pattern_defined = ! DECL_EXTERNAL (code_pattern);
23743     }
23744 
23745   /* We may be in the middle of deferred access check.  Disable it now.  */
23746   push_deferring_access_checks (dk_no_deferred);
23747 
23748   /* Unless an explicit instantiation directive has already determined
23749      the linkage of D, remember that a definition is available for
23750      this entity.  */
23751   if (pattern_defined
23752       && !DECL_INTERFACE_KNOWN (d)
23753       && !DECL_NOT_REALLY_EXTERN (d))
23754     mark_definable (d);
23755 
23756   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
23757   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
23758   input_location = DECL_SOURCE_LOCATION (d);
23759 
23760   /* If D is a member of an explicitly instantiated class template,
23761      and no definition is available, treat it like an implicit
23762      instantiation.  */
23763   if (!pattern_defined && expl_inst_class_mem_p
23764       && DECL_EXPLICIT_INSTANTIATION (d))
23765     {
23766       /* Leave linkage flags alone on instantiations with anonymous
23767 	 visibility.  */
23768       if (TREE_PUBLIC (d))
23769 	{
23770 	  DECL_NOT_REALLY_EXTERN (d) = 0;
23771 	  DECL_INTERFACE_KNOWN (d) = 0;
23772 	}
23773       SET_DECL_IMPLICIT_INSTANTIATION (d);
23774     }
23775 
23776   /* Defer all other templates, unless we have been explicitly
23777      forbidden from doing so.  */
23778   if (/* If there is no definition, we cannot instantiate the
23779 	 template.  */
23780       ! pattern_defined
23781       /* If it's OK to postpone instantiation, do so.  */
23782       || defer_ok
23783       /* If this is a static data member that will be defined
23784 	 elsewhere, we don't want to instantiate the entire data
23785 	 member, but we do want to instantiate the initializer so that
23786 	 we can substitute that elsewhere.  */
23787       || (external_p && VAR_P (d))
23788       /* Handle here a deleted function too, avoid generating
23789 	 its body (c++/61080).  */
23790       || deleted_p)
23791     {
23792       /* The definition of the static data member is now required so
23793 	 we must substitute the initializer.  */
23794       if (VAR_P (d)
23795 	  && !DECL_INITIAL (d)
23796 	  && DECL_INITIAL (code_pattern))
23797 	{
23798 	  tree ns;
23799 	  tree init;
23800 	  bool const_init = false;
23801 	  bool enter_context = DECL_CLASS_SCOPE_P (d);
23802 
23803 	  ns = decl_namespace_context (d);
23804 	  push_nested_namespace (ns);
23805 	  if (enter_context)
23806 	    push_nested_class (DECL_CONTEXT (d));
23807 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
23808 			      args,
23809 			      tf_warning_or_error, NULL_TREE,
23810 			      /*integral_constant_expression_p=*/false);
23811 	  /* If instantiating the initializer involved instantiating this
23812 	     again, don't call cp_finish_decl twice.  */
23813 	  if (!DECL_INITIAL (d))
23814 	    {
23815 	      /* Make sure the initializer is still constant, in case of
23816 		 circular dependency (template/instantiate6.C). */
23817 	      const_init
23818 		= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
23819 	      cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
23820 			      /*asmspec_tree=*/NULL_TREE,
23821 			      LOOKUP_ONLYCONVERTING);
23822 	    }
23823 	  if (enter_context)
23824 	    pop_nested_class ();
23825 	  pop_nested_namespace (ns);
23826 	}
23827 
23828       /* We restore the source position here because it's used by
23829 	 add_pending_template.  */
23830       input_location = saved_loc;
23831 
23832       if (at_eof && !pattern_defined
23833 	  && DECL_EXPLICIT_INSTANTIATION (d)
23834 	  && DECL_NOT_REALLY_EXTERN (d))
23835 	/* [temp.explicit]
23836 
23837 	   The definition of a non-exported function template, a
23838 	   non-exported member function template, or a non-exported
23839 	   member function or static data member of a class template
23840 	   shall be present in every translation unit in which it is
23841 	   explicitly instantiated.  */
23842 	permerror (input_location,  "explicit instantiation of %qD "
23843 		   "but no definition available", d);
23844 
23845       /* If we're in unevaluated context, we just wanted to get the
23846 	 constant value; this isn't an odr use, so don't queue
23847 	 a full instantiation.  */
23848       if (cp_unevaluated_operand != 0)
23849 	goto out;
23850       /* ??? Historically, we have instantiated inline functions, even
23851 	 when marked as "extern template".  */
23852       if (!(external_p && VAR_P (d)))
23853 	add_pending_template (d);
23854       goto out;
23855     }
23856   /* Tell the repository that D is available in this translation unit
23857      -- and see if it is supposed to be instantiated here.  */
23858   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
23859     {
23860       /* In a PCH file, despite the fact that the repository hasn't
23861 	 requested instantiation in the PCH it is still possible that
23862 	 an instantiation will be required in a file that includes the
23863 	 PCH.  */
23864       if (pch_file)
23865 	add_pending_template (d);
23866       /* Instantiate inline functions so that the inliner can do its
23867 	 job, even though we'll not be emitting a copy of this
23868 	 function.  */
23869       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
23870 	goto out;
23871     }
23872 
23873   bool push_to_top, nested;
23874   tree fn_context;
23875   fn_context = decl_function_context (d);
23876   if (LAMBDA_FUNCTION_P (d))
23877     /* tsubst_lambda_expr resolved any references to enclosing functions.  */
23878     fn_context = NULL_TREE;
23879   nested = current_function_decl != NULL_TREE;
23880   push_to_top = !(nested && fn_context == current_function_decl);
23881 
23882   vec<tree> omp_privatization_save;
23883   if (nested)
23884     save_omp_privatization_clauses (omp_privatization_save);
23885 
23886   if (push_to_top)
23887     push_to_top_level ();
23888   else
23889     {
23890       push_function_context ();
23891       cp_unevaluated_operand = 0;
23892       c_inhibit_evaluation_warnings = 0;
23893     }
23894 
23895   /* Mark D as instantiated so that recursive calls to
23896      instantiate_decl do not try to instantiate it again.  */
23897   DECL_TEMPLATE_INSTANTIATED (d) = 1;
23898 
23899   /* Regenerate the declaration in case the template has been modified
23900      by a subsequent redeclaration.  */
23901   regenerate_decl_from_template (d, td, args);
23902 
23903   /* We already set the file and line above.  Reset them now in case
23904      they changed as a result of calling regenerate_decl_from_template.  */
23905   input_location = DECL_SOURCE_LOCATION (d);
23906 
23907   if (VAR_P (d))
23908     {
23909       tree init;
23910       bool const_init = false;
23911 
23912       /* Clear out DECL_RTL; whatever was there before may not be right
23913 	 since we've reset the type of the declaration.  */
23914       SET_DECL_RTL (d, NULL);
23915       DECL_IN_AGGR_P (d) = 0;
23916 
23917       /* The initializer is placed in DECL_INITIAL by
23918 	 regenerate_decl_from_template so we don't need to
23919 	 push/pop_access_scope again here.  Pull it out so that
23920 	 cp_finish_decl can process it.  */
23921       init = DECL_INITIAL (d);
23922       DECL_INITIAL (d) = NULL_TREE;
23923       DECL_INITIALIZED_P (d) = 0;
23924 
23925       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
23926 	 initializer.  That function will defer actual emission until
23927 	 we have a chance to determine linkage.  */
23928       DECL_EXTERNAL (d) = 0;
23929 
23930       /* Enter the scope of D so that access-checking works correctly.  */
23931       bool enter_context = DECL_CLASS_SCOPE_P (d);
23932       if (enter_context)
23933         push_nested_class (DECL_CONTEXT (d));
23934 
23935       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
23936       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
23937 
23938       if (enter_context)
23939         pop_nested_class ();
23940 
23941       if (variable_template_p (gen_tmpl))
23942 	note_variable_template_instantiation (d);
23943     }
23944   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
23945     synthesize_method (d);
23946   else if (TREE_CODE (d) == FUNCTION_DECL)
23947     {
23948       /* Set up the list of local specializations.  */
23949       local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
23950       tree block = NULL_TREE;
23951 
23952       /* Set up context.  */
23953       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
23954 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
23955 	block = push_stmt_list ();
23956       else
23957 	start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
23958 
23959       /* Some typedefs referenced from within the template code need to be
23960 	 access checked at template instantiation time, i.e now. These
23961 	 types were added to the template at parsing time. Let's get those
23962 	 and perform the access checks then.  */
23963       perform_typedefs_access_check (DECL_TEMPLATE_RESULT (td),
23964 				     args);
23965 
23966       /* Create substitution entries for the parameters.  */
23967       register_parameter_specializations (code_pattern, d);
23968 
23969       /* Substitute into the body of the function.  */
23970       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
23971 	tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
23972 			tf_warning_or_error, tmpl);
23973       else
23974 	{
23975 	  tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
23976 		       tf_warning_or_error, tmpl,
23977 		       /*integral_constant_expression_p=*/false);
23978 
23979 	  /* Set the current input_location to the end of the function
23980 	     so that finish_function knows where we are.  */
23981 	  input_location
23982 	    = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
23983 
23984 	  /* Remember if we saw an infinite loop in the template.  */
23985 	  current_function_infinite_loop
23986 	    = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
23987 	}
23988 
23989       /* Finish the function.  */
23990       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
23991 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
23992 	DECL_SAVED_TREE (d) = pop_stmt_list (block);
23993       else
23994 	{
23995 	  d = finish_function (/*inline_p=*/false);
23996 	  expand_or_defer_fn (d);
23997 	}
23998 
23999       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
24000 	cp_check_omp_declare_reduction (d);
24001     }
24002 
24003   /* We're not deferring instantiation any more.  */
24004   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
24005 
24006   if (push_to_top)
24007     pop_from_top_level ();
24008   else
24009     pop_function_context ();
24010 
24011   if (nested)
24012     restore_omp_privatization_clauses (omp_privatization_save);
24013 
24014 out:
24015   pop_deferring_access_checks ();
24016   timevar_pop (TV_TEMPLATE_INST);
24017   pop_tinst_level ();
24018   input_location = saved_loc;
24019   cp_unevaluated_operand = saved_unevaluated_operand;
24020   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
24021 
24022   return d;
24023 }
24024 
24025 /* Run through the list of templates that we wish we could
24026    instantiate, and instantiate any we can.  RETRIES is the
24027    number of times we retry pending template instantiation.  */
24028 
24029 void
24030 instantiate_pending_templates (int retries)
24031 {
24032   int reconsider;
24033   location_t saved_loc = input_location;
24034 
24035   /* Instantiating templates may trigger vtable generation.  This in turn
24036      may require further template instantiations.  We place a limit here
24037      to avoid infinite loop.  */
24038   if (pending_templates && retries >= max_tinst_depth)
24039     {
24040       tree decl = pending_templates->tinst->maybe_get_node ();
24041 
24042       fatal_error (input_location,
24043 		   "template instantiation depth exceeds maximum of %d"
24044                    " instantiating %q+D, possibly from virtual table generation"
24045                    " (use -ftemplate-depth= to increase the maximum)",
24046                    max_tinst_depth, decl);
24047       if (TREE_CODE (decl) == FUNCTION_DECL)
24048 	/* Pretend that we defined it.  */
24049 	DECL_INITIAL (decl) = error_mark_node;
24050       return;
24051     }
24052 
24053   do
24054     {
24055       struct pending_template **t = &pending_templates;
24056       struct pending_template *last = NULL;
24057       reconsider = 0;
24058       while (*t)
24059 	{
24060 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
24061 	  bool complete = false;
24062 
24063 	  if (TYPE_P (instantiation))
24064 	    {
24065 	      if (!COMPLETE_TYPE_P (instantiation))
24066 		{
24067 		  instantiate_class_template (instantiation);
24068 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
24069 		    for (tree fld = TYPE_FIELDS (instantiation);
24070 			 fld; fld = TREE_CHAIN (fld))
24071 		      if ((VAR_P (fld)
24072 			   || (TREE_CODE (fld) == FUNCTION_DECL
24073 			       && !DECL_ARTIFICIAL (fld)))
24074 			  && DECL_TEMPLATE_INSTANTIATION (fld))
24075 			instantiate_decl (fld,
24076 					  /*defer_ok=*/false,
24077 					  /*expl_inst_class_mem_p=*/false);
24078 
24079 		  if (COMPLETE_TYPE_P (instantiation))
24080 		    reconsider = 1;
24081 		}
24082 
24083 	      complete = COMPLETE_TYPE_P (instantiation);
24084 	    }
24085 	  else
24086 	    {
24087 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
24088 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
24089 		{
24090 		  instantiation
24091 		    = instantiate_decl (instantiation,
24092 					/*defer_ok=*/false,
24093 					/*expl_inst_class_mem_p=*/false);
24094 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
24095 		    reconsider = 1;
24096 		}
24097 
24098 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
24099 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
24100 	    }
24101 
24102 	  if (complete)
24103 	    {
24104 	      /* If INSTANTIATION has been instantiated, then we don't
24105 		 need to consider it again in the future.  */
24106 	      struct pending_template *drop = *t;
24107 	      *t = (*t)->next;
24108 	      set_refcount_ptr (drop->tinst);
24109 	      pending_template_freelist ().free (drop);
24110 	    }
24111 	  else
24112 	    {
24113 	      last = *t;
24114 	      t = &(*t)->next;
24115 	    }
24116 	  tinst_depth = 0;
24117 	  set_refcount_ptr (current_tinst_level);
24118 	}
24119       last_pending_template = last;
24120     }
24121   while (reconsider);
24122 
24123   input_location = saved_loc;
24124 }
24125 
24126 /* Substitute ARGVEC into T, which is a list of initializers for
24127    either base class or a non-static data member.  The TREE_PURPOSEs
24128    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
24129    instantiate_decl.  */
24130 
24131 static tree
24132 tsubst_initializer_list (tree t, tree argvec)
24133 {
24134   tree inits = NULL_TREE;
24135   tree target_ctor = error_mark_node;
24136 
24137   for (; t; t = TREE_CHAIN (t))
24138     {
24139       tree decl;
24140       tree init;
24141       tree expanded_bases = NULL_TREE;
24142       tree expanded_arguments = NULL_TREE;
24143       int i, len = 1;
24144 
24145       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
24146         {
24147           tree expr;
24148           tree arg;
24149 
24150           /* Expand the base class expansion type into separate base
24151              classes.  */
24152           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
24153                                                  tf_warning_or_error,
24154                                                  NULL_TREE);
24155           if (expanded_bases == error_mark_node)
24156             continue;
24157 
24158           /* We'll be building separate TREE_LISTs of arguments for
24159              each base.  */
24160           len = TREE_VEC_LENGTH (expanded_bases);
24161           expanded_arguments = make_tree_vec (len);
24162           for (i = 0; i < len; i++)
24163             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
24164 
24165           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
24166              expand each argument in the TREE_VALUE of t.  */
24167           expr = make_node (EXPR_PACK_EXPANSION);
24168 	  PACK_EXPANSION_LOCAL_P (expr) = true;
24169           PACK_EXPANSION_PARAMETER_PACKS (expr) =
24170             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
24171 
24172 	  if (TREE_VALUE (t) == void_type_node)
24173 	    /* VOID_TYPE_NODE is used to indicate
24174 	       value-initialization.  */
24175 	    {
24176 	      for (i = 0; i < len; i++)
24177 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
24178 	    }
24179 	  else
24180 	    {
24181 	      /* Substitute parameter packs into each argument in the
24182 		 TREE_LIST.  */
24183 	      in_base_initializer = 1;
24184 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
24185 		{
24186 		  tree expanded_exprs;
24187 
24188 		  /* Expand the argument.  */
24189 		  SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
24190 		  expanded_exprs
24191 		    = tsubst_pack_expansion (expr, argvec,
24192 					     tf_warning_or_error,
24193 					     NULL_TREE);
24194 		  if (expanded_exprs == error_mark_node)
24195 		    continue;
24196 
24197 		  /* Prepend each of the expanded expressions to the
24198 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
24199 		  for (i = 0; i < len; i++)
24200 		    {
24201 		      TREE_VEC_ELT (expanded_arguments, i) =
24202 			tree_cons (NULL_TREE,
24203 				   TREE_VEC_ELT (expanded_exprs, i),
24204 				   TREE_VEC_ELT (expanded_arguments, i));
24205 		    }
24206 		}
24207 	      in_base_initializer = 0;
24208 
24209 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
24210 		 since we built them backwards.  */
24211 	      for (i = 0; i < len; i++)
24212 		{
24213 		  TREE_VEC_ELT (expanded_arguments, i) =
24214 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
24215 		}
24216 	    }
24217         }
24218 
24219       for (i = 0; i < len; ++i)
24220         {
24221           if (expanded_bases)
24222             {
24223               decl = TREE_VEC_ELT (expanded_bases, i);
24224               decl = expand_member_init (decl);
24225               init = TREE_VEC_ELT (expanded_arguments, i);
24226             }
24227           else
24228             {
24229 	      tree tmp;
24230               decl = tsubst_copy (TREE_PURPOSE (t), argvec,
24231                                   tf_warning_or_error, NULL_TREE);
24232 
24233               decl = expand_member_init (decl);
24234               if (decl && !DECL_P (decl))
24235                 in_base_initializer = 1;
24236 
24237 	      init = TREE_VALUE (t);
24238 	      tmp = init;
24239 	      if (init != void_type_node)
24240 		init = tsubst_expr (init, argvec,
24241 				    tf_warning_or_error, NULL_TREE,
24242 				    /*integral_constant_expression_p=*/false);
24243 	      if (init == NULL_TREE && tmp != NULL_TREE)
24244 		/* If we had an initializer but it instantiated to nothing,
24245 		   value-initialize the object.  This will only occur when
24246 		   the initializer was a pack expansion where the parameter
24247 		   packs used in that expansion were of length zero.  */
24248 		init = void_type_node;
24249               in_base_initializer = 0;
24250             }
24251 
24252 	  if (target_ctor != error_mark_node
24253 	      && init != error_mark_node)
24254 	    {
24255 	      error ("mem-initializer for %qD follows constructor delegation",
24256 		     decl);
24257 	      return inits;
24258 	    }
24259 	  /* Look for a target constructor. */
24260 	  if (init != error_mark_node
24261 	      && decl && CLASS_TYPE_P (decl)
24262 	      && same_type_p (decl, current_class_type))
24263 	    {
24264 	      maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
24265 	      if (inits)
24266 		{
24267 		  error ("constructor delegation follows mem-initializer for %qD",
24268 			 TREE_PURPOSE (inits));
24269 		  continue;
24270 		}
24271 	      target_ctor = init;
24272 	    }
24273 
24274           if (decl)
24275             {
24276               init = build_tree_list (decl, init);
24277               TREE_CHAIN (init) = inits;
24278               inits = init;
24279             }
24280         }
24281     }
24282   return inits;
24283 }
24284 
24285 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
24286 
24287 static void
24288 set_current_access_from_decl (tree decl)
24289 {
24290   if (TREE_PRIVATE (decl))
24291     current_access_specifier = access_private_node;
24292   else if (TREE_PROTECTED (decl))
24293     current_access_specifier = access_protected_node;
24294   else
24295     current_access_specifier = access_public_node;
24296 }
24297 
24298 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
24299    is the instantiation (which should have been created with
24300    start_enum) and ARGS are the template arguments to use.  */
24301 
24302 static void
24303 tsubst_enum (tree tag, tree newtag, tree args)
24304 {
24305   tree e;
24306 
24307   if (SCOPED_ENUM_P (newtag))
24308     begin_scope (sk_scoped_enum, newtag);
24309 
24310   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
24311     {
24312       tree value;
24313       tree decl;
24314 
24315       decl = TREE_VALUE (e);
24316       /* Note that in a template enum, the TREE_VALUE is the
24317 	 CONST_DECL, not the corresponding INTEGER_CST.  */
24318       value = tsubst_expr (DECL_INITIAL (decl),
24319 			   args, tf_warning_or_error, NULL_TREE,
24320 			   /*integral_constant_expression_p=*/true);
24321 
24322       /* Give this enumeration constant the correct access.  */
24323       set_current_access_from_decl (decl);
24324 
24325       /* Actually build the enumerator itself.  Here we're assuming that
24326 	 enumerators can't have dependent attributes.  */
24327       build_enumerator (DECL_NAME (decl), value, newtag,
24328 			DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
24329     }
24330 
24331   if (SCOPED_ENUM_P (newtag))
24332     finish_scope ();
24333 
24334   finish_enum_value_list (newtag);
24335   finish_enum (newtag);
24336 
24337   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
24338     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
24339 }
24340 
24341 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
24342    its type -- but without substituting the innermost set of template
24343    arguments.  So, innermost set of template parameters will appear in
24344    the type.  */
24345 
24346 tree
24347 get_mostly_instantiated_function_type (tree decl)
24348 {
24349   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
24350   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
24351 }
24352 
24353 /* Return truthvalue if we're processing a template different from
24354    the last one involved in diagnostics.  */
24355 bool
24356 problematic_instantiation_changed (void)
24357 {
24358   return current_tinst_level != last_error_tinst_level;
24359 }
24360 
24361 /* Remember current template involved in diagnostics.  */
24362 void
24363 record_last_problematic_instantiation (void)
24364 {
24365   set_refcount_ptr (last_error_tinst_level, current_tinst_level);
24366 }
24367 
24368 struct tinst_level *
24369 current_instantiation (void)
24370 {
24371   return current_tinst_level;
24372 }
24373 
24374 /* Return TRUE if current_function_decl is being instantiated, false
24375    otherwise.  */
24376 
24377 bool
24378 instantiating_current_function_p (void)
24379 {
24380   return (current_instantiation ()
24381 	  && (current_instantiation ()->maybe_get_node ()
24382 	      == current_function_decl));
24383 }
24384 
24385 /* [temp.param] Check that template non-type parm TYPE is of an allowable
24386    type.  Return false for ok, true for disallowed.  Issue error and
24387    inform messages under control of COMPLAIN.  */
24388 
24389 static bool
24390 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
24391 {
24392   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
24393     return false;
24394   else if (TYPE_PTR_P (type))
24395     return false;
24396   else if (TREE_CODE (type) == REFERENCE_TYPE
24397 	   && !TYPE_REF_IS_RVALUE (type))
24398     return false;
24399   else if (TYPE_PTRMEM_P (type))
24400     return false;
24401   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
24402     return false;
24403   else if (TREE_CODE (type) == TYPENAME_TYPE)
24404     return false;
24405   else if (TREE_CODE (type) == DECLTYPE_TYPE)
24406     return false;
24407   else if (TREE_CODE (type) == NULLPTR_TYPE)
24408     return false;
24409   /* A bound template template parm could later be instantiated to have a valid
24410      nontype parm type via an alias template.  */
24411   else if (cxx_dialect >= cxx11
24412 	   && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
24413     return false;
24414 
24415   if (complain & tf_error)
24416     {
24417       if (type == error_mark_node)
24418 	inform (input_location, "invalid template non-type parameter");
24419       else
24420 	error ("%q#T is not a valid type for a template non-type parameter",
24421 	       type);
24422     }
24423   return true;
24424 }
24425 
24426 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
24427    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
24428 
24429 static bool
24430 dependent_type_p_r (tree type)
24431 {
24432   tree scope;
24433 
24434   /* [temp.dep.type]
24435 
24436      A type is dependent if it is:
24437 
24438      -- a template parameter. Template template parameters are types
24439 	for us (since TYPE_P holds true for them) so we handle
24440 	them here.  */
24441   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
24442       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
24443     return true;
24444   /* -- a qualified-id with a nested-name-specifier which contains a
24445 	class-name that names a dependent type or whose unqualified-id
24446 	names a dependent type.  */
24447   if (TREE_CODE (type) == TYPENAME_TYPE)
24448     return true;
24449 
24450   /* An alias template specialization can be dependent even if the
24451      resulting type is not.  */
24452   if (dependent_alias_template_spec_p (type))
24453     return true;
24454 
24455   /* -- a cv-qualified type where the cv-unqualified type is
24456 	dependent.
24457      No code is necessary for this bullet; the code below handles
24458      cv-qualified types, and we don't want to strip aliases with
24459      TYPE_MAIN_VARIANT because of DR 1558.  */
24460   /* -- a compound type constructed from any dependent type.  */
24461   if (TYPE_PTRMEM_P (type))
24462     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
24463 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
24464 					   (type)));
24465   else if (TYPE_PTR_P (type)
24466 	   || TREE_CODE (type) == REFERENCE_TYPE)
24467     return dependent_type_p (TREE_TYPE (type));
24468   else if (TREE_CODE (type) == FUNCTION_TYPE
24469 	   || TREE_CODE (type) == METHOD_TYPE)
24470     {
24471       tree arg_type;
24472 
24473       if (dependent_type_p (TREE_TYPE (type)))
24474 	return true;
24475       for (arg_type = TYPE_ARG_TYPES (type);
24476 	   arg_type;
24477 	   arg_type = TREE_CHAIN (arg_type))
24478 	if (dependent_type_p (TREE_VALUE (arg_type)))
24479 	  return true;
24480       if (cxx_dialect >= cxx17)
24481 	/* A value-dependent noexcept-specifier makes the type dependent.  */
24482 	if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
24483 	  if (tree noex = TREE_PURPOSE (spec))
24484 	    /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
24485 	       affect overload resolution and treating it as dependent breaks
24486 	       things.  */
24487 	    if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
24488 		&& value_dependent_expression_p (noex))
24489 	      return true;
24490       return false;
24491     }
24492   /* -- an array type constructed from any dependent type or whose
24493 	size is specified by a constant expression that is
24494 	value-dependent.
24495 
24496         We checked for type- and value-dependence of the bounds in
24497         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
24498   if (TREE_CODE (type) == ARRAY_TYPE)
24499     {
24500       if (TYPE_DOMAIN (type)
24501 	  && dependent_type_p (TYPE_DOMAIN (type)))
24502 	return true;
24503       return dependent_type_p (TREE_TYPE (type));
24504     }
24505 
24506   /* -- a template-id in which either the template name is a template
24507      parameter ...  */
24508   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
24509     return true;
24510   /* ... or any of the template arguments is a dependent type or
24511 	an expression that is type-dependent or value-dependent.  */
24512   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
24513 	   && (any_dependent_template_arguments_p
24514 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
24515     return true;
24516 
24517   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
24518      dependent; if the argument of the `typeof' expression is not
24519      type-dependent, then it should already been have resolved.  */
24520   if (TREE_CODE (type) == TYPEOF_TYPE
24521       || TREE_CODE (type) == DECLTYPE_TYPE
24522       || TREE_CODE (type) == UNDERLYING_TYPE)
24523     return true;
24524 
24525   /* A template argument pack is dependent if any of its packed
24526      arguments are.  */
24527   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
24528     {
24529       tree args = ARGUMENT_PACK_ARGS (type);
24530       int i, len = TREE_VEC_LENGTH (args);
24531       for (i = 0; i < len; ++i)
24532         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
24533           return true;
24534     }
24535 
24536   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
24537      be template parameters.  */
24538   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
24539     return true;
24540 
24541   if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
24542     return true;
24543 
24544   /* The standard does not specifically mention types that are local
24545      to template functions or local classes, but they should be
24546      considered dependent too.  For example:
24547 
24548        template <int I> void f() {
24549 	 enum E { a = I };
24550 	 S<sizeof (E)> s;
24551        }
24552 
24553      The size of `E' cannot be known until the value of `I' has been
24554      determined.  Therefore, `E' must be considered dependent.  */
24555   scope = TYPE_CONTEXT (type);
24556   if (scope && TYPE_P (scope))
24557     return dependent_type_p (scope);
24558   /* Don't use type_dependent_expression_p here, as it can lead
24559      to infinite recursion trying to determine whether a lambda
24560      nested in a lambda is dependent (c++/47687).  */
24561   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
24562 	   && DECL_LANG_SPECIFIC (scope)
24563 	   && DECL_TEMPLATE_INFO (scope)
24564 	   && (any_dependent_template_arguments_p
24565 	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
24566     return true;
24567 
24568   /* Other types are non-dependent.  */
24569   return false;
24570 }
24571 
24572 /* Returns TRUE if TYPE is dependent, in the sense of
24573    [temp.dep.type].  Note that a NULL type is considered dependent.  */
24574 
24575 bool
24576 dependent_type_p (tree type)
24577 {
24578   /* If there are no template parameters in scope, then there can't be
24579      any dependent types.  */
24580   if (!processing_template_decl)
24581     {
24582       /* If we are not processing a template, then nobody should be
24583 	 providing us with a dependent type.  */
24584       gcc_assert (type);
24585       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
24586       return false;
24587     }
24588 
24589   /* If the type is NULL, we have not computed a type for the entity
24590      in question; in that case, the type is dependent.  */
24591   if (!type)
24592     return true;
24593 
24594   /* Erroneous types can be considered non-dependent.  */
24595   if (type == error_mark_node)
24596     return false;
24597 
24598   /* Getting here with global_type_node means we improperly called this
24599      function on the TREE_TYPE of an IDENTIFIER_NODE.  */
24600   gcc_checking_assert (type != global_type_node);
24601 
24602   /* If we have not already computed the appropriate value for TYPE,
24603      do so now.  */
24604   if (!TYPE_DEPENDENT_P_VALID (type))
24605     {
24606       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
24607       TYPE_DEPENDENT_P_VALID (type) = 1;
24608     }
24609 
24610   return TYPE_DEPENDENT_P (type);
24611 }
24612 
24613 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
24614    lookup.  In other words, a dependent type that is not the current
24615    instantiation.  */
24616 
24617 bool
24618 dependent_scope_p (tree scope)
24619 {
24620   return (scope && TYPE_P (scope) && dependent_type_p (scope)
24621 	  && !currently_open_class (scope));
24622 }
24623 
24624 /* T is a SCOPE_REF.  Return whether it represents a non-static member of
24625    an unknown base of 'this' (and is therefore instantiation-dependent).  */
24626 
24627 static bool
24628 unknown_base_ref_p (tree t)
24629 {
24630   if (!current_class_ptr)
24631     return false;
24632 
24633   tree mem = TREE_OPERAND (t, 1);
24634   if (shared_member_p (mem))
24635     return false;
24636 
24637   tree cur = current_nonlambda_class_type ();
24638   if (!any_dependent_bases_p (cur))
24639     return false;
24640 
24641   tree ctx = TREE_OPERAND (t, 0);
24642   if (DERIVED_FROM_P (ctx, cur))
24643     return false;
24644 
24645   return true;
24646 }
24647 
24648 /* T is a SCOPE_REF; return whether we need to consider it
24649     instantiation-dependent so that we can check access at instantiation
24650     time even though we know which member it resolves to.  */
24651 
24652 static bool
24653 instantiation_dependent_scope_ref_p (tree t)
24654 {
24655   if (DECL_P (TREE_OPERAND (t, 1))
24656       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
24657       && !unknown_base_ref_p (t)
24658       && accessible_in_template_p (TREE_OPERAND (t, 0),
24659 				   TREE_OPERAND (t, 1)))
24660     return false;
24661   else
24662     return true;
24663 }
24664 
24665 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
24666    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
24667    expression.  */
24668 
24669 /* Note that this predicate is not appropriate for general expressions;
24670    only constant expressions (that satisfy potential_constant_expression)
24671    can be tested for value dependence.  */
24672 
24673 bool
24674 value_dependent_expression_p (tree expression)
24675 {
24676   if (!processing_template_decl || expression == NULL_TREE)
24677     return false;
24678 
24679   /* A type-dependent expression is also value-dependent.  */
24680   if (type_dependent_expression_p (expression))
24681     return true;
24682 
24683   switch (TREE_CODE (expression))
24684     {
24685     case BASELINK:
24686       /* A dependent member function of the current instantiation.  */
24687       return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
24688 
24689     case FUNCTION_DECL:
24690       /* A dependent member function of the current instantiation.  */
24691       if (DECL_CLASS_SCOPE_P (expression)
24692 	  && dependent_type_p (DECL_CONTEXT (expression)))
24693 	return true;
24694       break;
24695 
24696     case IDENTIFIER_NODE:
24697       /* A name that has not been looked up -- must be dependent.  */
24698       return true;
24699 
24700     case TEMPLATE_PARM_INDEX:
24701       /* A non-type template parm.  */
24702       return true;
24703 
24704     case CONST_DECL:
24705       /* A non-type template parm.  */
24706       if (DECL_TEMPLATE_PARM_P (expression))
24707 	return true;
24708       return value_dependent_expression_p (DECL_INITIAL (expression));
24709 
24710     case VAR_DECL:
24711        /* A constant with literal type and is initialized
24712 	  with an expression that is value-dependent.  */
24713       if (DECL_DEPENDENT_INIT_P (expression)
24714 	  /* FIXME cp_finish_decl doesn't fold reference initializers.  */
24715 	  || TREE_CODE (TREE_TYPE (expression)) == REFERENCE_TYPE)
24716 	return true;
24717       if (DECL_HAS_VALUE_EXPR_P (expression))
24718 	{
24719 	  tree value_expr = DECL_VALUE_EXPR (expression);
24720 	  if (value_dependent_expression_p (value_expr))
24721 	    return true;
24722 	}
24723       return false;
24724 
24725     case DYNAMIC_CAST_EXPR:
24726     case STATIC_CAST_EXPR:
24727     case CONST_CAST_EXPR:
24728     case REINTERPRET_CAST_EXPR:
24729     case CAST_EXPR:
24730     case IMPLICIT_CONV_EXPR:
24731       /* These expressions are value-dependent if the type to which
24732 	 the cast occurs is dependent or the expression being casted
24733 	 is value-dependent.  */
24734       {
24735 	tree type = TREE_TYPE (expression);
24736 
24737 	if (dependent_type_p (type))
24738 	  return true;
24739 
24740 	/* A functional cast has a list of operands.  */
24741 	expression = TREE_OPERAND (expression, 0);
24742 	if (!expression)
24743 	  {
24744 	    /* If there are no operands, it must be an expression such
24745 	       as "int()". This should not happen for aggregate types
24746 	       because it would form non-constant expressions.  */
24747 	    gcc_assert (cxx_dialect >= cxx11
24748 			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
24749 
24750 	    return false;
24751 	  }
24752 
24753 	if (TREE_CODE (expression) == TREE_LIST)
24754 	  return any_value_dependent_elements_p (expression);
24755 
24756 	return value_dependent_expression_p (expression);
24757       }
24758 
24759     case SIZEOF_EXPR:
24760       if (SIZEOF_EXPR_TYPE_P (expression))
24761 	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
24762       /* FALLTHRU */
24763     case ALIGNOF_EXPR:
24764     case TYPEID_EXPR:
24765       /* A `sizeof' expression is value-dependent if the operand is
24766 	 type-dependent or is a pack expansion.  */
24767       expression = TREE_OPERAND (expression, 0);
24768       if (PACK_EXPANSION_P (expression))
24769         return true;
24770       else if (TYPE_P (expression))
24771 	return dependent_type_p (expression);
24772       return instantiation_dependent_uneval_expression_p (expression);
24773 
24774     case AT_ENCODE_EXPR:
24775       /* An 'encode' expression is value-dependent if the operand is
24776 	 type-dependent.  */
24777       expression = TREE_OPERAND (expression, 0);
24778       return dependent_type_p (expression);
24779 
24780     case NOEXCEPT_EXPR:
24781       expression = TREE_OPERAND (expression, 0);
24782       return instantiation_dependent_uneval_expression_p (expression);
24783 
24784     case SCOPE_REF:
24785       /* All instantiation-dependent expressions should also be considered
24786 	 value-dependent.  */
24787       return instantiation_dependent_scope_ref_p (expression);
24788 
24789     case COMPONENT_REF:
24790       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
24791 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
24792 
24793     case NONTYPE_ARGUMENT_PACK:
24794       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
24795          is value-dependent.  */
24796       {
24797         tree values = ARGUMENT_PACK_ARGS (expression);
24798         int i, len = TREE_VEC_LENGTH (values);
24799 
24800         for (i = 0; i < len; ++i)
24801           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
24802             return true;
24803 
24804         return false;
24805       }
24806 
24807     case TRAIT_EXPR:
24808       {
24809 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
24810 
24811 	if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
24812 	  return true;
24813 
24814 	if (!type2)
24815 	  return false;
24816 
24817 	if (TREE_CODE (type2) != TREE_LIST)
24818 	  return dependent_type_p (type2);
24819 
24820 	for (; type2; type2 = TREE_CHAIN (type2))
24821 	  if (dependent_type_p (TREE_VALUE (type2)))
24822 	    return true;
24823 
24824 	return false;
24825       }
24826 
24827     case MODOP_EXPR:
24828       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
24829 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
24830 
24831     case ARRAY_REF:
24832       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
24833 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
24834 
24835     case ADDR_EXPR:
24836       {
24837 	tree op = TREE_OPERAND (expression, 0);
24838 	return (value_dependent_expression_p (op)
24839 		|| has_value_dependent_address (op));
24840       }
24841 
24842     case REQUIRES_EXPR:
24843       /* Treat all requires-expressions as value-dependent so
24844          we don't try to fold them.  */
24845       return true;
24846 
24847     case TYPE_REQ:
24848       return dependent_type_p (TREE_OPERAND (expression, 0));
24849 
24850     case CALL_EXPR:
24851       {
24852 	if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
24853 	  return true;
24854 	tree fn = get_callee_fndecl (expression);
24855 	int i, nargs;
24856 	nargs = call_expr_nargs (expression);
24857 	for (i = 0; i < nargs; ++i)
24858 	  {
24859 	    tree op = CALL_EXPR_ARG (expression, i);
24860 	    /* In a call to a constexpr member function, look through the
24861 	       implicit ADDR_EXPR on the object argument so that it doesn't
24862 	       cause the call to be considered value-dependent.  We also
24863 	       look through it in potential_constant_expression.  */
24864 	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
24865 		&& DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
24866 		&& TREE_CODE (op) == ADDR_EXPR)
24867 	      op = TREE_OPERAND (op, 0);
24868 	    if (value_dependent_expression_p (op))
24869 	      return true;
24870 	  }
24871 	return false;
24872       }
24873 
24874     case TEMPLATE_ID_EXPR:
24875       return variable_concept_p (TREE_OPERAND (expression, 0));
24876 
24877     case CONSTRUCTOR:
24878       {
24879 	unsigned ix;
24880 	tree val;
24881 	if (dependent_type_p (TREE_TYPE (expression)))
24882 	  return true;
24883 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
24884 	  if (value_dependent_expression_p (val))
24885 	    return true;
24886 	return false;
24887       }
24888 
24889     case STMT_EXPR:
24890       /* Treat a GNU statement expression as dependent to avoid crashing
24891 	 under instantiate_non_dependent_expr; it can't be constant.  */
24892       return true;
24893 
24894     default:
24895       /* A constant expression is value-dependent if any subexpression is
24896 	 value-dependent.  */
24897       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
24898 	{
24899 	case tcc_reference:
24900 	case tcc_unary:
24901 	case tcc_comparison:
24902 	case tcc_binary:
24903 	case tcc_expression:
24904 	case tcc_vl_exp:
24905 	  {
24906 	    int i, len = cp_tree_operand_length (expression);
24907 
24908 	    for (i = 0; i < len; i++)
24909 	      {
24910 		tree t = TREE_OPERAND (expression, i);
24911 
24912 		/* In some cases, some of the operands may be missing.
24913 		   (For example, in the case of PREDECREMENT_EXPR, the
24914 		   amount to increment by may be missing.)  That doesn't
24915 		   make the expression dependent.  */
24916 		if (t && value_dependent_expression_p (t))
24917 		  return true;
24918 	      }
24919 	  }
24920 	  break;
24921 	default:
24922 	  break;
24923 	}
24924       break;
24925     }
24926 
24927   /* The expression is not value-dependent.  */
24928   return false;
24929 }
24930 
24931 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
24932    [temp.dep.expr].  Note that an expression with no type is
24933    considered dependent.  Other parts of the compiler arrange for an
24934    expression with type-dependent subexpressions to have no type, so
24935    this function doesn't have to be fully recursive.  */
24936 
24937 bool
24938 type_dependent_expression_p (tree expression)
24939 {
24940   if (!processing_template_decl)
24941     return false;
24942 
24943   if (expression == NULL_TREE || expression == error_mark_node)
24944     return false;
24945 
24946   STRIP_ANY_LOCATION_WRAPPER (expression);
24947 
24948   /* An unresolved name is always dependent.  */
24949   if (identifier_p (expression)
24950       || TREE_CODE (expression) == USING_DECL
24951       || TREE_CODE (expression) == WILDCARD_DECL)
24952     return true;
24953 
24954   /* A fold expression is type-dependent. */
24955   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
24956       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
24957       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
24958       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
24959     return true;
24960 
24961   /* Some expression forms are never type-dependent.  */
24962   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
24963       || TREE_CODE (expression) == SIZEOF_EXPR
24964       || TREE_CODE (expression) == ALIGNOF_EXPR
24965       || TREE_CODE (expression) == AT_ENCODE_EXPR
24966       || TREE_CODE (expression) == NOEXCEPT_EXPR
24967       || TREE_CODE (expression) == TRAIT_EXPR
24968       || TREE_CODE (expression) == TYPEID_EXPR
24969       || TREE_CODE (expression) == DELETE_EXPR
24970       || TREE_CODE (expression) == VEC_DELETE_EXPR
24971       || TREE_CODE (expression) == THROW_EXPR
24972       || TREE_CODE (expression) == REQUIRES_EXPR)
24973     return false;
24974 
24975   /* The types of these expressions depends only on the type to which
24976      the cast occurs.  */
24977   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
24978       || TREE_CODE (expression) == STATIC_CAST_EXPR
24979       || TREE_CODE (expression) == CONST_CAST_EXPR
24980       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
24981       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
24982       || TREE_CODE (expression) == CAST_EXPR)
24983     return dependent_type_p (TREE_TYPE (expression));
24984 
24985   /* The types of these expressions depends only on the type created
24986      by the expression.  */
24987   if (TREE_CODE (expression) == NEW_EXPR
24988       || TREE_CODE (expression) == VEC_NEW_EXPR)
24989     {
24990       /* For NEW_EXPR tree nodes created inside a template, either
24991 	 the object type itself or a TREE_LIST may appear as the
24992 	 operand 1.  */
24993       tree type = TREE_OPERAND (expression, 1);
24994       if (TREE_CODE (type) == TREE_LIST)
24995 	/* This is an array type.  We need to check array dimensions
24996 	   as well.  */
24997 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
24998 	       || value_dependent_expression_p
24999 		    (TREE_OPERAND (TREE_VALUE (type), 1));
25000       else
25001 	return dependent_type_p (type);
25002     }
25003 
25004   if (TREE_CODE (expression) == SCOPE_REF)
25005     {
25006       tree scope = TREE_OPERAND (expression, 0);
25007       tree name = TREE_OPERAND (expression, 1);
25008 
25009       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
25010 	 contains an identifier associated by name lookup with one or more
25011 	 declarations declared with a dependent type, or...a
25012 	 nested-name-specifier or qualified-id that names a member of an
25013 	 unknown specialization.  */
25014       return (type_dependent_expression_p (name)
25015 	      || dependent_scope_p (scope));
25016     }
25017 
25018   if (TREE_CODE (expression) == TEMPLATE_DECL
25019       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
25020     return uses_outer_template_parms (expression);
25021 
25022   if (TREE_CODE (expression) == STMT_EXPR)
25023     expression = stmt_expr_value_expr (expression);
25024 
25025   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
25026     {
25027       tree elt;
25028       unsigned i;
25029 
25030       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
25031 	{
25032 	  if (type_dependent_expression_p (elt))
25033 	    return true;
25034 	}
25035       return false;
25036     }
25037 
25038   /* A static data member of the current instantiation with incomplete
25039      array type is type-dependent, as the definition and specializations
25040      can have different bounds.  */
25041   if (VAR_P (expression)
25042       && DECL_CLASS_SCOPE_P (expression)
25043       && dependent_type_p (DECL_CONTEXT (expression))
25044       && VAR_HAD_UNKNOWN_BOUND (expression))
25045     return true;
25046 
25047   /* An array of unknown bound depending on a variadic parameter, eg:
25048 
25049      template<typename... Args>
25050        void foo (Args... args)
25051        {
25052          int arr[] = { args... };
25053        }
25054 
25055      template<int... vals>
25056        void bar ()
25057        {
25058          int arr[] = { vals... };
25059        }
25060 
25061      If the array has no length and has an initializer, it must be that
25062      we couldn't determine its length in cp_complete_array_type because
25063      it is dependent.  */
25064   if (VAR_P (expression)
25065       && TREE_TYPE (expression) != NULL_TREE
25066       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
25067       && !TYPE_DOMAIN (TREE_TYPE (expression))
25068       && DECL_INITIAL (expression))
25069    return true;
25070 
25071   /* A function or variable template-id is type-dependent if it has any
25072      dependent template arguments.  */
25073   if (VAR_OR_FUNCTION_DECL_P (expression)
25074       && DECL_LANG_SPECIFIC (expression)
25075       && DECL_TEMPLATE_INFO (expression))
25076     {
25077       /* Consider the innermost template arguments, since those are the ones
25078 	 that come from the template-id; the template arguments for the
25079 	 enclosing class do not make it type-dependent unless they are used in
25080 	 the type of the decl.  */
25081       if (PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (expression))
25082 	  && (any_dependent_template_arguments_p
25083 	      (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
25084 	return true;
25085     }
25086 
25087   /* Otherwise, if the function decl isn't from a dependent scope, it can't be
25088      type-dependent.  Checking this is important for functions with auto return
25089      type, which looks like a dependent type.  */
25090   if (TREE_CODE (expression) == FUNCTION_DECL
25091       && !(DECL_CLASS_SCOPE_P (expression)
25092 	   && dependent_type_p (DECL_CONTEXT (expression)))
25093       && !(DECL_LANG_SPECIFIC (expression)
25094 	   && DECL_FRIEND_P (expression)
25095 	   && (!DECL_FRIEND_CONTEXT (expression)
25096 	       || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
25097       && !DECL_LOCAL_FUNCTION_P (expression))
25098     {
25099       gcc_assert (!dependent_type_p (TREE_TYPE (expression))
25100 		  || undeduced_auto_decl (expression));
25101       return false;
25102     }
25103 
25104   /* Always dependent, on the number of arguments if nothing else.  */
25105   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
25106     return true;
25107 
25108   if (TREE_TYPE (expression) == unknown_type_node)
25109     {
25110       if (TREE_CODE (expression) == ADDR_EXPR)
25111 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
25112       if (TREE_CODE (expression) == COMPONENT_REF
25113 	  || TREE_CODE (expression) == OFFSET_REF)
25114 	{
25115 	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
25116 	    return true;
25117 	  expression = TREE_OPERAND (expression, 1);
25118 	  if (identifier_p (expression))
25119 	    return false;
25120 	}
25121       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
25122       if (TREE_CODE (expression) == SCOPE_REF)
25123 	return false;
25124 
25125       if (BASELINK_P (expression))
25126 	{
25127 	  if (BASELINK_OPTYPE (expression)
25128 	      && dependent_type_p (BASELINK_OPTYPE (expression)))
25129 	    return true;
25130 	  expression = BASELINK_FUNCTIONS (expression);
25131 	}
25132 
25133       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
25134 	{
25135 	  if (any_dependent_template_arguments_p
25136 	      (TREE_OPERAND (expression, 1)))
25137 	    return true;
25138 	  expression = TREE_OPERAND (expression, 0);
25139 	  if (identifier_p (expression))
25140 	    return true;
25141 	}
25142 
25143       gcc_assert (TREE_CODE (expression) == OVERLOAD
25144 		  || TREE_CODE (expression) == FUNCTION_DECL);
25145 
25146       for (lkp_iterator iter (expression); iter; ++iter)
25147 	if (type_dependent_expression_p (*iter))
25148 	  return true;
25149 
25150       return false;
25151     }
25152 
25153   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
25154 
25155   /* Dependent type attributes might not have made it from the decl to
25156      the type yet.  */
25157   if (DECL_P (expression)
25158       && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
25159     return true;
25160 
25161   return (dependent_type_p (TREE_TYPE (expression)));
25162 }
25163 
25164 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
25165    type-dependent if the expression refers to a member of the current
25166    instantiation and the type of the referenced member is dependent, or the
25167    class member access expression refers to a member of an unknown
25168    specialization.
25169 
25170    This function returns true if the OBJECT in such a class member access
25171    expression is of an unknown specialization.  */
25172 
25173 bool
25174 type_dependent_object_expression_p (tree object)
25175 {
25176   /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
25177      dependent.  */
25178   if (TREE_CODE (object) == IDENTIFIER_NODE)
25179     return true;
25180   tree scope = TREE_TYPE (object);
25181   return (!scope || dependent_scope_p (scope));
25182 }
25183 
25184 /* walk_tree callback function for instantiation_dependent_expression_p,
25185    below.  Returns non-zero if a dependent subexpression is found.  */
25186 
25187 static tree
25188 instantiation_dependent_r (tree *tp, int *walk_subtrees,
25189 			   void * /*data*/)
25190 {
25191   if (TYPE_P (*tp))
25192     {
25193       /* We don't have to worry about decltype currently because decltype
25194 	 of an instantiation-dependent expr is a dependent type.  This
25195 	 might change depending on the resolution of DR 1172.  */
25196       *walk_subtrees = false;
25197       return NULL_TREE;
25198     }
25199   enum tree_code code = TREE_CODE (*tp);
25200   switch (code)
25201     {
25202       /* Don't treat an argument list as dependent just because it has no
25203 	 TREE_TYPE.  */
25204     case TREE_LIST:
25205     case TREE_VEC:
25206       return NULL_TREE;
25207 
25208     case TEMPLATE_PARM_INDEX:
25209       return *tp;
25210 
25211       /* Handle expressions with type operands.  */
25212     case SIZEOF_EXPR:
25213     case ALIGNOF_EXPR:
25214     case TYPEID_EXPR:
25215     case AT_ENCODE_EXPR:
25216       {
25217 	tree op = TREE_OPERAND (*tp, 0);
25218 	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
25219 	  op = TREE_TYPE (op);
25220 	if (TYPE_P (op))
25221 	  {
25222 	    if (dependent_type_p (op))
25223 	      return *tp;
25224 	    else
25225 	      {
25226 		*walk_subtrees = false;
25227 		return NULL_TREE;
25228 	      }
25229 	  }
25230 	break;
25231       }
25232 
25233     case COMPONENT_REF:
25234       if (identifier_p (TREE_OPERAND (*tp, 1)))
25235 	/* In a template, finish_class_member_access_expr creates a
25236 	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
25237 	   type-dependent, so that we can check access control at
25238 	   instantiation time (PR 42277).  See also Core issue 1273.  */
25239 	return *tp;
25240       break;
25241 
25242     case SCOPE_REF:
25243       if (instantiation_dependent_scope_ref_p (*tp))
25244 	return *tp;
25245       else
25246 	break;
25247 
25248       /* Treat statement-expressions as dependent.  */
25249     case BIND_EXPR:
25250       return *tp;
25251 
25252       /* Treat requires-expressions as dependent. */
25253     case REQUIRES_EXPR:
25254       return *tp;
25255 
25256     case CALL_EXPR:
25257       /* Treat calls to function concepts as dependent. */
25258       if (function_concept_check_p (*tp))
25259         return *tp;
25260       break;
25261 
25262     case TEMPLATE_ID_EXPR:
25263       /* And variable concepts.  */
25264       if (variable_concept_p (TREE_OPERAND (*tp, 0)))
25265 	return *tp;
25266       break;
25267 
25268     default:
25269       break;
25270     }
25271 
25272   if (type_dependent_expression_p (*tp))
25273     return *tp;
25274   else
25275     return NULL_TREE;
25276 }
25277 
25278 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
25279    sense defined by the ABI:
25280 
25281    "An expression is instantiation-dependent if it is type-dependent
25282    or value-dependent, or it has a subexpression that is type-dependent
25283    or value-dependent."
25284 
25285    Except don't actually check value-dependence for unevaluated expressions,
25286    because in sizeof(i) we don't care about the value of i.  Checking
25287    type-dependence will in turn check value-dependence of array bounds/template
25288    arguments as needed.  */
25289 
25290 bool
25291 instantiation_dependent_uneval_expression_p (tree expression)
25292 {
25293   tree result;
25294 
25295   if (!processing_template_decl)
25296     return false;
25297 
25298   if (expression == error_mark_node)
25299     return false;
25300 
25301   result = cp_walk_tree_without_duplicates (&expression,
25302 					    instantiation_dependent_r, NULL);
25303   return result != NULL_TREE;
25304 }
25305 
25306 /* As above, but also check value-dependence of the expression as a whole.  */
25307 
25308 bool
25309 instantiation_dependent_expression_p (tree expression)
25310 {
25311   return (instantiation_dependent_uneval_expression_p (expression)
25312 	  || value_dependent_expression_p (expression));
25313 }
25314 
25315 /* Like type_dependent_expression_p, but it also works while not processing
25316    a template definition, i.e. during substitution or mangling.  */
25317 
25318 bool
25319 type_dependent_expression_p_push (tree expr)
25320 {
25321   bool b;
25322   ++processing_template_decl;
25323   b = type_dependent_expression_p (expr);
25324   --processing_template_decl;
25325   return b;
25326 }
25327 
25328 /* Returns TRUE if ARGS contains a type-dependent expression.  */
25329 
25330 bool
25331 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
25332 {
25333   unsigned int i;
25334   tree arg;
25335 
25336   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
25337     {
25338       if (type_dependent_expression_p (arg))
25339 	return true;
25340     }
25341   return false;
25342 }
25343 
25344 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
25345    expressions) contains any type-dependent expressions.  */
25346 
25347 bool
25348 any_type_dependent_elements_p (const_tree list)
25349 {
25350   for (; list; list = TREE_CHAIN (list))
25351     if (type_dependent_expression_p (TREE_VALUE (list)))
25352       return true;
25353 
25354   return false;
25355 }
25356 
25357 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
25358    expressions) contains any value-dependent expressions.  */
25359 
25360 bool
25361 any_value_dependent_elements_p (const_tree list)
25362 {
25363   for (; list; list = TREE_CHAIN (list))
25364     if (value_dependent_expression_p (TREE_VALUE (list)))
25365       return true;
25366 
25367   return false;
25368 }
25369 
25370 /* Returns TRUE if the ARG (a template argument) is dependent.  */
25371 
25372 bool
25373 dependent_template_arg_p (tree arg)
25374 {
25375   if (!processing_template_decl)
25376     return false;
25377 
25378   /* Assume a template argument that was wrongly written by the user
25379      is dependent. This is consistent with what
25380      any_dependent_template_arguments_p [that calls this function]
25381      does.  */
25382   if (!arg || arg == error_mark_node)
25383     return true;
25384 
25385   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
25386     arg = argument_pack_select_arg (arg);
25387 
25388   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
25389     return true;
25390   if (TREE_CODE (arg) == TEMPLATE_DECL)
25391     {
25392       if (DECL_TEMPLATE_PARM_P (arg))
25393 	return true;
25394       /* A member template of a dependent class is not necessarily
25395 	 type-dependent, but it is a dependent template argument because it
25396 	 will be a member of an unknown specialization to that template.  */
25397       tree scope = CP_DECL_CONTEXT (arg);
25398       return TYPE_P (scope) && dependent_type_p (scope);
25399     }
25400   else if (ARGUMENT_PACK_P (arg))
25401     {
25402       tree args = ARGUMENT_PACK_ARGS (arg);
25403       int i, len = TREE_VEC_LENGTH (args);
25404       for (i = 0; i < len; ++i)
25405         {
25406           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
25407             return true;
25408         }
25409 
25410       return false;
25411     }
25412   else if (TYPE_P (arg))
25413     return dependent_type_p (arg);
25414   else
25415     return (type_dependent_expression_p (arg)
25416 	    || value_dependent_expression_p (arg));
25417 }
25418 
25419 /* Returns true if ARGS (a collection of template arguments) contains
25420    any types that require structural equality testing.  */
25421 
25422 bool
25423 any_template_arguments_need_structural_equality_p (tree args)
25424 {
25425   int i;
25426   int j;
25427 
25428   if (!args)
25429     return false;
25430   if (args == error_mark_node)
25431     return true;
25432 
25433   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25434     {
25435       tree level = TMPL_ARGS_LEVEL (args, i + 1);
25436       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25437 	{
25438 	  tree arg = TREE_VEC_ELT (level, j);
25439 	  tree packed_args = NULL_TREE;
25440 	  int k, len = 1;
25441 
25442 	  if (ARGUMENT_PACK_P (arg))
25443 	    {
25444 	      /* Look inside the argument pack.  */
25445 	      packed_args = ARGUMENT_PACK_ARGS (arg);
25446 	      len = TREE_VEC_LENGTH (packed_args);
25447 	    }
25448 
25449 	  for (k = 0; k < len; ++k)
25450 	    {
25451 	      if (packed_args)
25452 		arg = TREE_VEC_ELT (packed_args, k);
25453 
25454 	      if (error_operand_p (arg))
25455 		return true;
25456 	      else if (TREE_CODE (arg) == TEMPLATE_DECL)
25457 		continue;
25458 	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
25459 		return true;
25460 	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
25461 		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
25462 		return true;
25463 	    }
25464 	}
25465     }
25466 
25467   return false;
25468 }
25469 
25470 /* Returns true if ARGS (a collection of template arguments) contains
25471    any dependent arguments.  */
25472 
25473 bool
25474 any_dependent_template_arguments_p (const_tree args)
25475 {
25476   int i;
25477   int j;
25478 
25479   if (!args)
25480     return false;
25481   if (args == error_mark_node)
25482     return true;
25483 
25484   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25485     {
25486       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
25487       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25488 	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
25489 	  return true;
25490     }
25491 
25492   return false;
25493 }
25494 
25495 /* Returns true if ARGS contains any errors.  */
25496 
25497 bool
25498 any_erroneous_template_args_p (const_tree args)
25499 {
25500   int i;
25501   int j;
25502 
25503   if (args == error_mark_node)
25504     return true;
25505 
25506   if (args && TREE_CODE (args) != TREE_VEC)
25507     {
25508       if (tree ti = get_template_info (args))
25509 	args = TI_ARGS (ti);
25510       else
25511 	args = NULL_TREE;
25512     }
25513 
25514   if (!args)
25515     return false;
25516 
25517   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25518     {
25519       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
25520       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25521 	if (error_operand_p (TREE_VEC_ELT (level, j)))
25522 	  return true;
25523     }
25524 
25525   return false;
25526 }
25527 
25528 /* Returns TRUE if the template TMPL is type-dependent.  */
25529 
25530 bool
25531 dependent_template_p (tree tmpl)
25532 {
25533   if (TREE_CODE (tmpl) == OVERLOAD)
25534     {
25535       for (lkp_iterator iter (tmpl); iter; ++iter)
25536 	if (dependent_template_p (*iter))
25537 	  return true;
25538       return false;
25539     }
25540 
25541   /* Template template parameters are dependent.  */
25542   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
25543       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
25544     return true;
25545   /* So are names that have not been looked up.  */
25546   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
25547     return true;
25548   return false;
25549 }
25550 
25551 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
25552 
25553 bool
25554 dependent_template_id_p (tree tmpl, tree args)
25555 {
25556   return (dependent_template_p (tmpl)
25557 	  || any_dependent_template_arguments_p (args));
25558 }
25559 
25560 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
25561    are dependent.  */
25562 
25563 bool
25564 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
25565 {
25566   int i;
25567 
25568   if (!processing_template_decl)
25569     return false;
25570 
25571   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
25572     {
25573       tree decl = TREE_VEC_ELT (declv, i);
25574       tree init = TREE_VEC_ELT (initv, i);
25575       tree cond = TREE_VEC_ELT (condv, i);
25576       tree incr = TREE_VEC_ELT (incrv, i);
25577 
25578       if (type_dependent_expression_p (decl)
25579 	  || TREE_CODE (decl) == SCOPE_REF)
25580 	return true;
25581 
25582       if (init && type_dependent_expression_p (init))
25583 	return true;
25584 
25585       if (type_dependent_expression_p (cond))
25586 	return true;
25587 
25588       if (COMPARISON_CLASS_P (cond)
25589 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
25590 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
25591 	return true;
25592 
25593       if (TREE_CODE (incr) == MODOP_EXPR)
25594 	{
25595 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
25596 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
25597 	    return true;
25598 	}
25599       else if (type_dependent_expression_p (incr))
25600 	return true;
25601       else if (TREE_CODE (incr) == MODIFY_EXPR)
25602 	{
25603 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
25604 	    return true;
25605 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
25606 	    {
25607 	      tree t = TREE_OPERAND (incr, 1);
25608 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
25609 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
25610 		return true;
25611 	    }
25612 	}
25613     }
25614 
25615   return false;
25616 }
25617 
25618 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
25619    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
25620    no such TYPE can be found.  Note that this function peers inside
25621    uninstantiated templates and therefore should be used only in
25622    extremely limited situations.  ONLY_CURRENT_P restricts this
25623    peering to the currently open classes hierarchy (which is required
25624    when comparing types).  */
25625 
25626 tree
25627 resolve_typename_type (tree type, bool only_current_p)
25628 {
25629   tree scope;
25630   tree name;
25631   tree decl;
25632   int quals;
25633   tree pushed_scope;
25634   tree result;
25635 
25636   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
25637 
25638   scope = TYPE_CONTEXT (type);
25639   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
25640   gcc_checking_assert (uses_template_parms (scope));
25641 
25642   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
25643      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
25644      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
25645      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
25646      identifier  of the TYPENAME_TYPE anymore.
25647      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
25648      TYPENAME_TYPE instead, we avoid messing up with a possible
25649      typedef variant case.  */
25650   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
25651 
25652   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
25653      it first before we can figure out what NAME refers to.  */
25654   if (TREE_CODE (scope) == TYPENAME_TYPE)
25655     {
25656       if (TYPENAME_IS_RESOLVING_P (scope))
25657 	/* Given a class template A with a dependent base with nested type C,
25658 	   typedef typename A::C::C C will land us here, as trying to resolve
25659 	   the initial A::C leads to the local C typedef, which leads back to
25660 	   A::C::C.  So we break the recursion now.  */
25661 	return type;
25662       else
25663 	scope = resolve_typename_type (scope, only_current_p);
25664     }
25665   /* If we don't know what SCOPE refers to, then we cannot resolve the
25666      TYPENAME_TYPE.  */
25667   if (!CLASS_TYPE_P (scope))
25668     return type;
25669   /* If this is a typedef, we don't want to look inside (c++/11987).  */
25670   if (typedef_variant_p (type))
25671     return type;
25672   /* If SCOPE isn't the template itself, it will not have a valid
25673      TYPE_FIELDS list.  */
25674   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
25675     /* scope is either the template itself or a compatible instantiation
25676        like X<T>, so look up the name in the original template.  */
25677     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
25678   /* If scope has no fields, it can't be a current instantiation.  Check this
25679      before currently_open_class to avoid infinite recursion (71515).  */
25680   if (!TYPE_FIELDS (scope))
25681     return type;
25682   /* If the SCOPE is not the current instantiation, there's no reason
25683      to look inside it.  */
25684   if (only_current_p && !currently_open_class (scope))
25685     return type;
25686   /* Enter the SCOPE so that name lookup will be resolved as if we
25687      were in the class definition.  In particular, SCOPE will no
25688      longer be considered a dependent type.  */
25689   pushed_scope = push_scope (scope);
25690   /* Look up the declaration.  */
25691   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
25692 			tf_warning_or_error);
25693 
25694   result = NULL_TREE;
25695 
25696   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
25697      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
25698   tree fullname = TYPENAME_TYPE_FULLNAME (type);
25699   if (!decl)
25700     /*nop*/;
25701   else if (identifier_p (fullname)
25702 	   && TREE_CODE (decl) == TYPE_DECL)
25703     {
25704       result = TREE_TYPE (decl);
25705       if (result == error_mark_node)
25706 	result = NULL_TREE;
25707     }
25708   else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
25709 	   && DECL_CLASS_TEMPLATE_P (decl))
25710     {
25711       /* Obtain the template and the arguments.  */
25712       tree tmpl = TREE_OPERAND (fullname, 0);
25713       if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
25714 	{
25715 	  /* We get here with a plain identifier because a previous tentative
25716 	     parse of the nested-name-specifier as part of a ptr-operator saw
25717 	     ::template X<A>.  The use of ::template is necessary in a
25718 	     ptr-operator, but wrong in a declarator-id.
25719 
25720 	     [temp.names]: In a qualified-id of a declarator-id, the keyword
25721 	     template shall not appear at the top level.  */
25722 	  pedwarn (EXPR_LOC_OR_LOC (fullname, input_location), OPT_Wpedantic,
25723 		   "keyword %<template%> not allowed in declarator-id");
25724 	  tmpl = decl;
25725 	}
25726       tree args = TREE_OPERAND (fullname, 1);
25727       /* Instantiate the template.  */
25728       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
25729 				      /*entering_scope=*/true,
25730 				      tf_error | tf_user);
25731       if (result == error_mark_node)
25732 	result = NULL_TREE;
25733     }
25734 
25735   /* Leave the SCOPE.  */
25736   if (pushed_scope)
25737     pop_scope (pushed_scope);
25738 
25739   /* If we failed to resolve it, return the original typename.  */
25740   if (!result)
25741     return type;
25742 
25743   /* If lookup found a typename type, resolve that too.  */
25744   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
25745     {
25746       /* Ill-formed programs can cause infinite recursion here, so we
25747 	 must catch that.  */
25748       TYPENAME_IS_RESOLVING_P (result) = 1;
25749       result = resolve_typename_type (result, only_current_p);
25750       TYPENAME_IS_RESOLVING_P (result) = 0;
25751     }
25752 
25753   /* Qualify the resulting type.  */
25754   quals = cp_type_quals (type);
25755   if (quals)
25756     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
25757 
25758   return result;
25759 }
25760 
25761 /* EXPR is an expression which is not type-dependent.  Return a proxy
25762    for EXPR that can be used to compute the types of larger
25763    expressions containing EXPR.  */
25764 
25765 tree
25766 build_non_dependent_expr (tree expr)
25767 {
25768   tree orig_expr = expr;
25769   tree inner_expr;
25770 
25771   /* When checking, try to get a constant value for all non-dependent
25772      expressions in order to expose bugs in *_dependent_expression_p
25773      and constexpr.  This can affect code generation, see PR70704, so
25774      only do this for -fchecking=2.  */
25775   if (flag_checking > 1
25776       && cxx_dialect >= cxx11
25777       /* Don't do this during nsdmi parsing as it can lead to
25778 	 unexpected recursive instantiations.  */
25779       && !parsing_nsdmi ()
25780       /* Don't do this during concept expansion either and for
25781          the same reason.  */
25782       && !expanding_concept ())
25783     fold_non_dependent_expr (expr);
25784 
25785   STRIP_ANY_LOCATION_WRAPPER (expr);
25786 
25787   /* Preserve OVERLOADs; the functions must be available to resolve
25788      types.  */
25789   inner_expr = expr;
25790   if (TREE_CODE (inner_expr) == STMT_EXPR)
25791     inner_expr = stmt_expr_value_expr (inner_expr);
25792   if (TREE_CODE (inner_expr) == ADDR_EXPR)
25793     inner_expr = TREE_OPERAND (inner_expr, 0);
25794   if (TREE_CODE (inner_expr) == COMPONENT_REF)
25795     inner_expr = TREE_OPERAND (inner_expr, 1);
25796   if (is_overloaded_fn (inner_expr)
25797       || TREE_CODE (inner_expr) == OFFSET_REF)
25798     return orig_expr;
25799   /* There is no need to return a proxy for a variable.  */
25800   if (VAR_P (expr))
25801     return orig_expr;
25802   /* Preserve string constants; conversions from string constants to
25803      "char *" are allowed, even though normally a "const char *"
25804      cannot be used to initialize a "char *".  */
25805   if (TREE_CODE (expr) == STRING_CST)
25806     return orig_expr;
25807   /* Preserve void and arithmetic constants, as an optimization -- there is no
25808      reason to create a new node.  */
25809   if (TREE_CODE (expr) == VOID_CST
25810       || TREE_CODE (expr) == INTEGER_CST
25811       || TREE_CODE (expr) == REAL_CST)
25812     return orig_expr;
25813   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
25814      There is at least one place where we want to know that a
25815      particular expression is a throw-expression: when checking a ?:
25816      expression, there are special rules if the second or third
25817      argument is a throw-expression.  */
25818   if (TREE_CODE (expr) == THROW_EXPR)
25819     return orig_expr;
25820 
25821   /* Don't wrap an initializer list, we need to be able to look inside.  */
25822   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
25823     return orig_expr;
25824 
25825   /* Don't wrap a dummy object, we need to be able to test for it.  */
25826   if (is_dummy_object (expr))
25827     return orig_expr;
25828 
25829   if (TREE_CODE (expr) == COND_EXPR)
25830     return build3 (COND_EXPR,
25831 		   TREE_TYPE (expr),
25832 		   TREE_OPERAND (expr, 0),
25833 		   (TREE_OPERAND (expr, 1)
25834 		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
25835 		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
25836 		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
25837   if (TREE_CODE (expr) == COMPOUND_EXPR
25838       && !COMPOUND_EXPR_OVERLOADED (expr))
25839     return build2 (COMPOUND_EXPR,
25840 		   TREE_TYPE (expr),
25841 		   TREE_OPERAND (expr, 0),
25842 		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
25843 
25844   /* If the type is unknown, it can't really be non-dependent */
25845   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
25846 
25847   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
25848   return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
25849 		     TREE_TYPE (expr), expr);
25850 }
25851 
25852 /* ARGS is a vector of expressions as arguments to a function call.
25853    Replace the arguments with equivalent non-dependent expressions.
25854    This modifies ARGS in place.  */
25855 
25856 void
25857 make_args_non_dependent (vec<tree, va_gc> *args)
25858 {
25859   unsigned int ix;
25860   tree arg;
25861 
25862   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
25863     {
25864       tree newarg = build_non_dependent_expr (arg);
25865       if (newarg != arg)
25866 	(*args)[ix] = newarg;
25867     }
25868 }
25869 
25870 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
25871    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
25872    parms.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
25873 
25874 static tree
25875 make_auto_1 (tree name, bool set_canonical)
25876 {
25877   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
25878   TYPE_NAME (au) = build_decl (input_location,
25879 			       TYPE_DECL, name, au);
25880   TYPE_STUB_DECL (au) = TYPE_NAME (au);
25881   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
25882     (0, processing_template_decl + 1, processing_template_decl + 1,
25883      TYPE_NAME (au), NULL_TREE);
25884   if (set_canonical)
25885     TYPE_CANONICAL (au) = canonical_type_parameter (au);
25886   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
25887   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
25888 
25889   return au;
25890 }
25891 
25892 tree
25893 make_decltype_auto (void)
25894 {
25895   return make_auto_1 (decltype_auto_identifier, true);
25896 }
25897 
25898 tree
25899 make_auto (void)
25900 {
25901   return make_auto_1 (auto_identifier, true);
25902 }
25903 
25904 /* Return a C++17 deduction placeholder for class template TMPL.  */
25905 
25906 tree
25907 make_template_placeholder (tree tmpl)
25908 {
25909   tree t = make_auto_1 (DECL_NAME (tmpl), true);
25910   CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
25911   return t;
25912 }
25913 
25914 /* True iff T is a C++17 class template deduction placeholder.  */
25915 
25916 bool
25917 template_placeholder_p (tree t)
25918 {
25919   return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
25920 }
25921 
25922 /* Make a "constrained auto" type-specifier. This is an
25923    auto type with constraints that must be associated after
25924    deduction.  The constraint is formed from the given
25925    CONC and its optional sequence of arguments, which are
25926    non-null if written as partial-concept-id.  */
25927 
25928 tree
25929 make_constrained_auto (tree con, tree args)
25930 {
25931   tree type = make_auto_1 (auto_identifier, false);
25932 
25933   /* Build the constraint. */
25934   tree tmpl = DECL_TI_TEMPLATE (con);
25935   tree expr = VAR_P (con) ? tmpl : ovl_make (tmpl);
25936   expr = build_concept_check (expr, type, args);
25937 
25938   tree constr = normalize_expression (expr);
25939   PLACEHOLDER_TYPE_CONSTRAINTS (type) = constr;
25940 
25941   /* Our canonical type depends on the constraint.  */
25942   TYPE_CANONICAL (type) = canonical_type_parameter (type);
25943 
25944   /* Attach the constraint to the type declaration. */
25945   tree decl = TYPE_NAME (type);
25946   return decl;
25947 }
25948 
25949 /* Given type ARG, return std::initializer_list<ARG>.  */
25950 
25951 static tree
25952 listify (tree arg)
25953 {
25954   tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
25955 
25956   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
25957     {
25958       gcc_rich_location richloc (input_location);
25959       maybe_add_include_fixit (&richloc, "<initializer_list>");
25960       error_at (&richloc,
25961 		"deducing from brace-enclosed initializer list"
25962 		" requires %<#include <initializer_list>%>");
25963 
25964       return error_mark_node;
25965     }
25966   tree argvec = make_tree_vec (1);
25967   TREE_VEC_ELT (argvec, 0) = arg;
25968 
25969   return lookup_template_class (std_init_list, argvec, NULL_TREE,
25970 				NULL_TREE, 0, tf_warning_or_error);
25971 }
25972 
25973 /* Replace auto in TYPE with std::initializer_list<auto>.  */
25974 
25975 static tree
25976 listify_autos (tree type, tree auto_node)
25977 {
25978   tree init_auto = listify (auto_node);
25979   tree argvec = make_tree_vec (1);
25980   TREE_VEC_ELT (argvec, 0) = init_auto;
25981   if (processing_template_decl)
25982     argvec = add_to_template_args (current_template_args (), argvec);
25983   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
25984 }
25985 
25986 /* Hash traits for hashing possibly constrained 'auto'
25987    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
25988 
25989 struct auto_hash : default_hash_traits<tree>
25990 {
25991   static inline hashval_t hash (tree);
25992   static inline bool equal (tree, tree);
25993 };
25994 
25995 /* Hash the 'auto' T.  */
25996 
25997 inline hashval_t
25998 auto_hash::hash (tree t)
25999 {
26000   if (tree c = PLACEHOLDER_TYPE_CONSTRAINTS (t))
26001     /* Matching constrained-type-specifiers denote the same template
26002        parameter, so hash the constraint.  */
26003     return hash_placeholder_constraint (c);
26004   else
26005     /* But unconstrained autos are all separate, so just hash the pointer.  */
26006     return iterative_hash_object (t, 0);
26007 }
26008 
26009 /* Compare two 'auto's.  */
26010 
26011 inline bool
26012 auto_hash::equal (tree t1, tree t2)
26013 {
26014   if (t1 == t2)
26015     return true;
26016 
26017   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
26018   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
26019 
26020   /* Two unconstrained autos are distinct.  */
26021   if (!c1 || !c2)
26022     return false;
26023 
26024   return equivalent_placeholder_constraints (c1, c2);
26025 }
26026 
26027 /* for_each_template_parm callback for extract_autos: if t is a (possibly
26028    constrained) auto, add it to the vector.  */
26029 
26030 static int
26031 extract_autos_r (tree t, void *data)
26032 {
26033   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
26034   if (is_auto (t))
26035     {
26036       /* All the autos were built with index 0; fix that up now.  */
26037       tree *p = hash.find_slot (t, INSERT);
26038       unsigned idx;
26039       if (*p)
26040 	/* If this is a repeated constrained-type-specifier, use the index we
26041 	   chose before.  */
26042 	idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
26043       else
26044 	{
26045 	  /* Otherwise this is new, so use the current count.  */
26046 	  *p = t;
26047 	  idx = hash.elements () - 1;
26048 	}
26049       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
26050     }
26051 
26052   /* Always keep walking.  */
26053   return 0;
26054 }
26055 
26056 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
26057    says they can appear anywhere in the type.  */
26058 
26059 static tree
26060 extract_autos (tree type)
26061 {
26062   hash_set<tree> visited;
26063   hash_table<auto_hash> hash (2);
26064 
26065   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
26066 
26067   tree tree_vec = make_tree_vec (hash.elements());
26068   for (hash_table<auto_hash>::iterator iter = hash.begin();
26069        iter != hash.end(); ++iter)
26070     {
26071       tree elt = *iter;
26072       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
26073       TREE_VEC_ELT (tree_vec, i)
26074 	= build_tree_list (NULL_TREE, TYPE_NAME (elt));
26075     }
26076 
26077   return tree_vec;
26078 }
26079 
26080 /* The stem for deduction guide names.  */
26081 const char *const dguide_base = "__dguide_";
26082 
26083 /* Return the name for a deduction guide for class template TMPL.  */
26084 
26085 tree
26086 dguide_name (tree tmpl)
26087 {
26088   tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
26089   tree tname = TYPE_IDENTIFIER (type);
26090   char *buf = (char *) alloca (1 + strlen (dguide_base)
26091 			       + IDENTIFIER_LENGTH (tname));
26092   memcpy (buf, dguide_base, strlen (dguide_base));
26093   memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
26094 	  IDENTIFIER_LENGTH (tname) + 1);
26095   tree dname = get_identifier (buf);
26096   TREE_TYPE (dname) = type;
26097   return dname;
26098 }
26099 
26100 /* True if NAME is the name of a deduction guide.  */
26101 
26102 bool
26103 dguide_name_p (tree name)
26104 {
26105   return (TREE_CODE (name) == IDENTIFIER_NODE
26106 	  && TREE_TYPE (name)
26107 	  && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
26108 		       strlen (dguide_base)));
26109 }
26110 
26111 /* True if FN is a deduction guide.  */
26112 
26113 bool
26114 deduction_guide_p (const_tree fn)
26115 {
26116   if (DECL_P (fn))
26117     if (tree name = DECL_NAME (fn))
26118       return dguide_name_p (name);
26119   return false;
26120 }
26121 
26122 /* True if FN is the copy deduction guide, i.e. A(A)->A.  */
26123 
26124 bool
26125 copy_guide_p (const_tree fn)
26126 {
26127   gcc_assert (deduction_guide_p (fn));
26128   if (!DECL_ARTIFICIAL (fn))
26129     return false;
26130   tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
26131   return (TREE_CHAIN (parms) == void_list_node
26132 	  && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
26133 }
26134 
26135 /* True if FN is a guide generated from a constructor template.  */
26136 
26137 bool
26138 template_guide_p (const_tree fn)
26139 {
26140   gcc_assert (deduction_guide_p (fn));
26141   if (!DECL_ARTIFICIAL (fn))
26142     return false;
26143   tree tmpl = DECL_TI_TEMPLATE (fn);
26144   if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
26145     return PRIMARY_TEMPLATE_P (org);
26146   return false;
26147 }
26148 
26149 /* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
26150    LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
26151    template parameter types.  Note that the handling of template template
26152    parameters relies on current_template_parms being set appropriately for the
26153    new template.  */
26154 
26155 static tree
26156 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
26157 		       tree tsubst_args, tsubst_flags_t complain)
26158 {
26159   if (olddecl == error_mark_node)
26160     return error_mark_node;
26161 
26162   tree oldidx = get_template_parm_index (olddecl);
26163 
26164   tree newtype;
26165   if (TREE_CODE (olddecl) == TYPE_DECL
26166       || TREE_CODE (olddecl) == TEMPLATE_DECL)
26167     {
26168       tree oldtype = TREE_TYPE (olddecl);
26169       newtype = cxx_make_type (TREE_CODE (oldtype));
26170       TYPE_MAIN_VARIANT (newtype) = newtype;
26171       if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
26172 	TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
26173 	  = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
26174     }
26175   else
26176     {
26177       newtype = TREE_TYPE (olddecl);
26178       if (type_uses_auto (newtype))
26179 	{
26180 	  // Substitute once to fix references to other template parameters.
26181 	  newtype = tsubst (newtype, tsubst_args,
26182 			    complain|tf_partial, NULL_TREE);
26183 	  // Now substitute again to reduce the level of the auto.
26184 	  newtype = tsubst (newtype, current_template_args (),
26185 			    complain, NULL_TREE);
26186 	}
26187       else
26188 	newtype = tsubst (newtype, tsubst_args,
26189 			  complain, NULL_TREE);
26190     }
26191 
26192   tree newdecl
26193     = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
26194 		  DECL_NAME (olddecl), newtype);
26195   SET_DECL_TEMPLATE_PARM_P (newdecl);
26196 
26197   tree newidx;
26198   if (TREE_CODE (olddecl) == TYPE_DECL
26199       || TREE_CODE (olddecl) == TEMPLATE_DECL)
26200     {
26201       newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
26202 	= build_template_parm_index (index, level, level,
26203 				     newdecl, newtype);
26204       TEMPLATE_PARM_PARAMETER_PACK (newidx)
26205 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
26206       TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
26207       TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
26208 
26209       if (TREE_CODE (olddecl) == TEMPLATE_DECL)
26210 	{
26211 	  DECL_TEMPLATE_RESULT (newdecl)
26212 	    = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
26213 			  DECL_NAME (olddecl), newtype);
26214 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
26215 	  // First create a copy (ttargs) of tsubst_args with an
26216 	  // additional level for the template template parameter's own
26217 	  // template parameters (ttparms).
26218 	  tree ttparms = (INNERMOST_TEMPLATE_PARMS
26219 			  (DECL_TEMPLATE_PARMS (olddecl)));
26220 	  const int depth = TMPL_ARGS_DEPTH (tsubst_args);
26221 	  tree ttargs = make_tree_vec (depth + 1);
26222 	  for (int i = 0; i < depth; ++i)
26223 	    TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
26224 	  TREE_VEC_ELT (ttargs, depth)
26225 	    = template_parms_level_to_args (ttparms);
26226 	  // Substitute ttargs into ttparms to fix references to
26227 	  // other template parameters.
26228 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
26229 						 complain|tf_partial);
26230 	  // Now substitute again with args based on tparms, to reduce
26231 	  // the level of the ttparms.
26232 	  ttargs = current_template_args ();
26233 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
26234 						 complain);
26235 	  // Finally, tack the adjusted parms onto tparms.
26236 	  ttparms = tree_cons (size_int (depth), ttparms,
26237 			       current_template_parms);
26238 	  DECL_TEMPLATE_PARMS (newdecl) = ttparms;
26239 	}
26240     }
26241   else
26242     {
26243       tree oldconst = TEMPLATE_PARM_DECL (oldidx);
26244       tree newconst
26245 	= build_decl (DECL_SOURCE_LOCATION (oldconst),
26246 		      TREE_CODE (oldconst),
26247 		      DECL_NAME (oldconst), newtype);
26248       TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
26249 	= TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
26250       SET_DECL_TEMPLATE_PARM_P (newconst);
26251       newidx = build_template_parm_index (index, level, level,
26252 					  newconst, newtype);
26253       TEMPLATE_PARM_PARAMETER_PACK (newidx)
26254 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
26255       DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
26256     }
26257 
26258   return newdecl;
26259 }
26260 
26261 /* Returns a C++17 class deduction guide template based on the constructor
26262    CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
26263    guide, or REFERENCE_TYPE for an implicit copy/move guide.  */
26264 
26265 static tree
26266 build_deduction_guide (tree ctor, tree outer_args, tsubst_flags_t complain)
26267 {
26268   tree type, tparms, targs, fparms, fargs, ci;
26269   bool memtmpl = false;
26270   bool explicit_p;
26271   location_t loc;
26272   tree fn_tmpl = NULL_TREE;
26273 
26274   if (TYPE_P (ctor))
26275     {
26276       type = ctor;
26277       bool copy_p = TREE_CODE (type) == REFERENCE_TYPE;
26278       if (copy_p)
26279 	{
26280 	  type = TREE_TYPE (type);
26281 	  fparms = tree_cons (NULL_TREE, type, void_list_node);
26282 	}
26283       else
26284 	fparms = void_list_node;
26285 
26286       tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
26287       tparms = DECL_TEMPLATE_PARMS (ctmpl);
26288       targs = CLASSTYPE_TI_ARGS (type);
26289       ci = NULL_TREE;
26290       fargs = NULL_TREE;
26291       loc = DECL_SOURCE_LOCATION (ctmpl);
26292       explicit_p = false;
26293     }
26294   else
26295     {
26296       ++processing_template_decl;
26297       bool ok = true;
26298 
26299       fn_tmpl
26300 	= (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
26301 	   : DECL_TI_TEMPLATE (ctor));
26302       if (outer_args)
26303 	fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
26304       ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
26305 
26306       type = DECL_CONTEXT (ctor);
26307 
26308       tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
26309       /* If type is a member class template, DECL_TI_ARGS (ctor) will have
26310 	 fully specialized args for the enclosing class.  Strip those off, as
26311 	 the deduction guide won't have those template parameters.  */
26312       targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
26313 						TMPL_PARMS_DEPTH (tparms));
26314       /* Discard the 'this' parameter.  */
26315       fparms = FUNCTION_ARG_CHAIN (ctor);
26316       fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
26317       ci = get_constraints (ctor);
26318       loc = DECL_SOURCE_LOCATION (ctor);
26319       explicit_p = DECL_NONCONVERTING_P (ctor);
26320 
26321       if (PRIMARY_TEMPLATE_P (fn_tmpl))
26322 	{
26323 	  memtmpl = true;
26324 
26325 	  /* For a member template constructor, we need to flatten the two
26326 	     template parameter lists into one, and then adjust the function
26327 	     signature accordingly.  This gets...complicated.  */
26328 	  tree save_parms = current_template_parms;
26329 
26330 	  /* For a member template we should have two levels of parms/args, one
26331 	     for the class and one for the constructor.  We stripped
26332 	     specialized args for further enclosing classes above.  */
26333 	  const int depth = 2;
26334 	  gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
26335 
26336 	  /* Template args for translating references to the two-level template
26337 	     parameters into references to the one-level template parameters we
26338 	     are creating.  */
26339 	  tree tsubst_args = copy_node (targs);
26340 	  TMPL_ARGS_LEVEL (tsubst_args, depth)
26341 	    = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
26342 
26343 	  /* Template parms for the constructor template.  */
26344 	  tree ftparms = TREE_VALUE (tparms);
26345 	  unsigned flen = TREE_VEC_LENGTH (ftparms);
26346 	  /* Template parms for the class template.  */
26347 	  tparms = TREE_CHAIN (tparms);
26348 	  tree ctparms = TREE_VALUE (tparms);
26349 	  unsigned clen = TREE_VEC_LENGTH (ctparms);
26350 	  /* Template parms for the deduction guide start as a copy of the
26351 	     template parms for the class.  We set current_template_parms for
26352 	     lookup_template_class_1.  */
26353 	  current_template_parms = tparms = copy_node (tparms);
26354 	  tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
26355 	  for (unsigned i = 0; i < clen; ++i)
26356 	    TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
26357 
26358 	  /* Now we need to rewrite the constructor parms to append them to the
26359 	     class parms.  */
26360 	  for (unsigned i = 0; i < flen; ++i)
26361 	    {
26362 	      unsigned index = i + clen;
26363 	      unsigned level = 1;
26364 	      tree oldelt = TREE_VEC_ELT (ftparms, i);
26365 	      tree olddecl = TREE_VALUE (oldelt);
26366 	      tree newdecl = rewrite_template_parm (olddecl, index, level,
26367 						    tsubst_args, complain);
26368 	      if (newdecl == error_mark_node)
26369 		ok = false;
26370 	      tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
26371 						 tsubst_args, complain, ctor);
26372 	      tree list = build_tree_list (newdef, newdecl);
26373 	      TEMPLATE_PARM_CONSTRAINTS (list)
26374 		= tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
26375 					  tsubst_args, complain, ctor);
26376 	      TREE_VEC_ELT (new_vec, index) = list;
26377 	      TMPL_ARG (tsubst_args, depth, i) = template_parm_to_arg (list);
26378 	    }
26379 
26380 	  /* Now we have a final set of template parms to substitute into the
26381 	     function signature.  */
26382 	  targs = template_parms_to_args (tparms);
26383 	  fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
26384 				     complain, ctor);
26385 	  fargs = tsubst (fargs, tsubst_args, complain, ctor);
26386 	  if (ci)
26387 	    ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
26388 
26389 	  current_template_parms = save_parms;
26390 	}
26391 
26392       --processing_template_decl;
26393       if (!ok)
26394 	return error_mark_node;
26395     }
26396 
26397   if (!memtmpl)
26398     {
26399       /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
26400       tparms = copy_node (tparms);
26401       INNERMOST_TEMPLATE_PARMS (tparms)
26402 	= copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
26403     }
26404 
26405   tree fntype = build_function_type (type, fparms);
26406   tree ded_fn = build_lang_decl_loc (loc,
26407 				     FUNCTION_DECL,
26408 				     dguide_name (type), fntype);
26409   DECL_ARGUMENTS (ded_fn) = fargs;
26410   DECL_ARTIFICIAL (ded_fn) = true;
26411   DECL_NONCONVERTING_P (ded_fn) = explicit_p;
26412   tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
26413   DECL_ARTIFICIAL (ded_tmpl) = true;
26414   DECL_TEMPLATE_RESULT (ded_tmpl) = ded_fn;
26415   TREE_TYPE (ded_tmpl) = TREE_TYPE (ded_fn);
26416   DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
26417   DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
26418   if (DECL_P (ctor))
26419     DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
26420   if (ci)
26421     set_constraints (ded_tmpl, ci);
26422 
26423   return ded_tmpl;
26424 }
26425 
26426 /* Deduce template arguments for the class template placeholder PTYPE for
26427    template TMPL based on the initializer INIT, and return the resulting
26428    type.  */
26429 
26430 static tree
26431 do_class_deduction (tree ptype, tree tmpl, tree init, int flags,
26432 		    tsubst_flags_t complain)
26433 {
26434   if (!DECL_CLASS_TEMPLATE_P (tmpl))
26435     {
26436       /* We should have handled this in the caller.  */
26437       if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
26438 	return ptype;
26439       if (complain & tf_error)
26440 	error ("non-class template %qT used without template arguments", tmpl);
26441       return error_mark_node;
26442     }
26443 
26444   tree type = TREE_TYPE (tmpl);
26445 
26446   bool try_list_ctor = false;
26447 
26448   vec<tree,va_gc> *args;
26449   if (init == NULL_TREE
26450       || TREE_CODE (init) == TREE_LIST)
26451     args = make_tree_vector_from_list (init);
26452   else if (BRACE_ENCLOSED_INITIALIZER_P (init))
26453     {
26454       try_list_ctor = TYPE_HAS_LIST_CTOR (type);
26455       if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
26456 	{
26457 	  /* As an exception, the first phase in 16.3.1.7 (considering the
26458 	     initializer list as a single argument) is omitted if the
26459 	     initializer list consists of a single expression of type cv U,
26460 	     where U is a specialization of C or a class derived from a
26461 	     specialization of C.  */
26462 	  tree elt = CONSTRUCTOR_ELT (init, 0)->value;
26463 	  tree etype = TREE_TYPE (elt);
26464 
26465 	  tree tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
26466 	  tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
26467 	  int err = unify (tparms, targs, type, etype,
26468 			   UNIFY_ALLOW_DERIVED, /*explain*/false);
26469 	  if (err == 0)
26470 	    try_list_ctor = false;
26471 	  ggc_free (targs);
26472 	}
26473       if (try_list_ctor || is_std_init_list (type))
26474 	args = make_tree_vector_single (init);
26475       else
26476 	args = make_tree_vector_from_ctor (init);
26477     }
26478   else
26479     args = make_tree_vector_single (init);
26480 
26481   tree dname = dguide_name (tmpl);
26482   tree cands = lookup_qualified_name (CP_DECL_CONTEXT (tmpl), dname,
26483 				      /*type*/false, /*complain*/false,
26484 				      /*hidden*/false);
26485   bool elided = false;
26486   if (cands == error_mark_node)
26487     cands = NULL_TREE;
26488 
26489   /* Prune explicit deduction guides in copy-initialization context.  */
26490   if (flags & LOOKUP_ONLYCONVERTING)
26491     {
26492       for (lkp_iterator iter (cands); !elided && iter; ++iter)
26493 	if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
26494 	  elided = true;
26495 
26496       if (elided)
26497 	{
26498 	  /* Found a nonconverting guide, prune the candidates.  */
26499 	  tree pruned = NULL_TREE;
26500 	  for (lkp_iterator iter (cands); iter; ++iter)
26501 	    if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
26502 	      pruned = lookup_add (*iter, pruned);
26503 
26504 	  cands = pruned;
26505 	}
26506     }
26507 
26508   tree outer_args = NULL_TREE;
26509   if (DECL_CLASS_SCOPE_P (tmpl)
26510       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (tmpl)))
26511     {
26512       outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
26513       type = TREE_TYPE (most_general_template (tmpl));
26514     }
26515 
26516   bool saw_ctor = false;
26517   // FIXME cache artificial deduction guides
26518   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
26519     {
26520       /* Skip inherited constructors.  */
26521       if (iter.using_p ())
26522 	continue;
26523 
26524       tree guide = build_deduction_guide (*iter, outer_args, complain);
26525       if (guide == error_mark_node)
26526 	return error_mark_node;
26527       if ((flags & LOOKUP_ONLYCONVERTING)
26528 	  && DECL_NONCONVERTING_P (STRIP_TEMPLATE (guide)))
26529 	elided = true;
26530       else
26531 	cands = lookup_add (guide, cands);
26532 
26533       saw_ctor = true;
26534     }
26535 
26536   tree call = error_mark_node;
26537 
26538   /* If this is list-initialization and the class has a list constructor, first
26539      try deducing from the list as a single argument, as [over.match.list].  */
26540   tree list_cands = NULL_TREE;
26541   if (try_list_ctor && cands)
26542     for (lkp_iterator iter (cands); iter; ++iter)
26543       {
26544 	tree dg = *iter;
26545 	if (is_list_ctor (dg))
26546 	  list_cands = lookup_add (dg, list_cands);
26547       }
26548   if (list_cands)
26549     {
26550       ++cp_unevaluated_operand;
26551       call = build_new_function_call (list_cands, &args, tf_decltype);
26552       --cp_unevaluated_operand;
26553 
26554       if (call == error_mark_node)
26555 	{
26556 	  /* That didn't work, now try treating the list as a sequence of
26557 	     arguments.  */
26558 	  release_tree_vector (args);
26559 	  args = make_tree_vector_from_ctor (init);
26560 	}
26561     }
26562 
26563   /* Maybe generate an implicit deduction guide.  */
26564   if (call == error_mark_node && args->length () < 2)
26565     {
26566       tree gtype = NULL_TREE;
26567 
26568       if (args->length () == 1)
26569 	/* Generate a copy guide.  */
26570 	gtype = build_reference_type (type);
26571       else if (!saw_ctor)
26572 	/* Generate a default guide.  */
26573 	gtype = type;
26574 
26575       if (gtype)
26576 	{
26577 	  tree guide = build_deduction_guide (gtype, outer_args, complain);
26578 	  if (guide == error_mark_node)
26579 	    return error_mark_node;
26580 	  cands = lookup_add (guide, cands);
26581 	}
26582     }
26583 
26584   if (elided && !cands)
26585     {
26586       error ("cannot deduce template arguments for copy-initialization"
26587 	     " of %qT, as it has no non-explicit deduction guides or "
26588 	     "user-declared constructors", type);
26589       return error_mark_node;
26590     }
26591   else if (!cands && call == error_mark_node)
26592     {
26593       error ("cannot deduce template arguments of %qT, as it has no viable "
26594 	     "deduction guides", type);
26595       return error_mark_node;
26596     }
26597 
26598   if (call == error_mark_node)
26599     {
26600       ++cp_unevaluated_operand;
26601       call = build_new_function_call (cands, &args, tf_decltype);
26602       --cp_unevaluated_operand;
26603     }
26604 
26605   if (call == error_mark_node && (complain & tf_warning_or_error))
26606     {
26607       error ("class template argument deduction failed:");
26608 
26609       ++cp_unevaluated_operand;
26610       call = build_new_function_call (cands, &args, complain | tf_decltype);
26611       --cp_unevaluated_operand;
26612 
26613       if (elided)
26614 	inform (input_location, "explicit deduction guides not considered "
26615 		"for copy-initialization");
26616     }
26617 
26618   release_tree_vector (args);
26619 
26620   return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
26621 }
26622 
26623 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
26624    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
26625    The CONTEXT determines the context in which auto deduction is performed
26626    and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
26627    OUTER_TARGS are used during template argument deduction
26628    (context == adc_unify) to properly substitute the result, and is ignored
26629    in other contexts.
26630 
26631    For partial-concept-ids, extra args may be appended to the list of deduced
26632    template arguments prior to determining constraint satisfaction.  */
26633 
26634 tree
26635 do_auto_deduction (tree type, tree init, tree auto_node,
26636                    tsubst_flags_t complain, auto_deduction_context context,
26637 		   tree outer_targs, int flags)
26638 {
26639   tree targs;
26640 
26641   if (init == error_mark_node)
26642     return error_mark_node;
26643 
26644   if (init && type_dependent_expression_p (init)
26645       && context != adc_unify)
26646     /* Defining a subset of type-dependent expressions that we can deduce
26647        from ahead of time isn't worth the trouble.  */
26648     return type;
26649 
26650   /* Similarly, we can't deduce from another undeduced decl.  */
26651   if (init && undeduced_auto_decl (init))
26652     return type;
26653 
26654   if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
26655     /* C++17 class template argument deduction.  */
26656     return do_class_deduction (type, tmpl, init, flags, complain);
26657 
26658   if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
26659     /* Nothing we can do with this, even in deduction context.  */
26660     return type;
26661 
26662   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
26663      with either a new invented type template parameter U or, if the
26664      initializer is a braced-init-list (8.5.4), with
26665      std::initializer_list<U>.  */
26666   if (BRACE_ENCLOSED_INITIALIZER_P (init))
26667     {
26668       if (!DIRECT_LIST_INIT_P (init))
26669 	type = listify_autos (type, auto_node);
26670       else if (CONSTRUCTOR_NELTS (init) == 1)
26671 	init = CONSTRUCTOR_ELT (init, 0)->value;
26672       else
26673 	{
26674           if (complain & tf_warning_or_error)
26675             {
26676 	      if (permerror (input_location, "direct-list-initialization of "
26677 			     "%<auto%> requires exactly one element"))
26678 	        inform (input_location,
26679 		        "for deduction to %<std::initializer_list%>, use copy-"
26680 		        "list-initialization (i.e. add %<=%> before the %<{%>)");
26681             }
26682 	  type = listify_autos (type, auto_node);
26683 	}
26684     }
26685 
26686   if (type == error_mark_node)
26687     return error_mark_node;
26688 
26689   init = resolve_nondeduced_context (init, complain);
26690 
26691   if (context == adc_decomp_type
26692       && auto_node == type
26693       && init != error_mark_node
26694       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
26695     /* [dcl.decomp]/1 - if decomposition declaration has no ref-qualifiers
26696        and initializer has array type, deduce cv-qualified array type.  */
26697     return cp_build_qualified_type_real (TREE_TYPE (init), TYPE_QUALS (type),
26698 					 complain);
26699   else if (AUTO_IS_DECLTYPE (auto_node))
26700     {
26701       bool id = (DECL_P (init)
26702 		 || ((TREE_CODE (init) == COMPONENT_REF
26703 		      || TREE_CODE (init) == SCOPE_REF)
26704 		     && !REF_PARENTHESIZED_P (init)));
26705       targs = make_tree_vec (1);
26706       TREE_VEC_ELT (targs, 0)
26707 	= finish_decltype_type (init, id, tf_warning_or_error);
26708       if (type != auto_node)
26709 	{
26710           if (complain & tf_error)
26711 	    error ("%qT as type rather than plain %<decltype(auto)%>", type);
26712 	  return error_mark_node;
26713 	}
26714     }
26715   else
26716     {
26717       tree parms = build_tree_list (NULL_TREE, type);
26718       tree tparms;
26719 
26720       if (flag_concepts)
26721 	tparms = extract_autos (type);
26722       else
26723 	{
26724 	  tparms = make_tree_vec (1);
26725 	  TREE_VEC_ELT (tparms, 0)
26726 	    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
26727 	}
26728 
26729       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
26730       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
26731 				       DEDUCE_CALL, LOOKUP_NORMAL,
26732 				       NULL, /*explain_p=*/false);
26733       if (val > 0)
26734 	{
26735 	  if (processing_template_decl)
26736 	    /* Try again at instantiation time.  */
26737 	    return type;
26738 	  if (type && type != error_mark_node
26739 	      && (complain & tf_error))
26740 	    /* If type is error_mark_node a diagnostic must have been
26741 	       emitted by now.  Also, having a mention to '<type error>'
26742 	       in the diagnostic is not really useful to the user.  */
26743 	    {
26744 	      if (cfun && auto_node == current_function_auto_return_pattern
26745 		  && LAMBDA_FUNCTION_P (current_function_decl))
26746 		error ("unable to deduce lambda return type from %qE", init);
26747 	      else
26748 		error ("unable to deduce %qT from %qE", type, init);
26749 	      type_unification_real (tparms, targs, parms, &init, 1, 0,
26750 				     DEDUCE_CALL, LOOKUP_NORMAL,
26751 				     NULL, /*explain_p=*/true);
26752 	    }
26753 	  return error_mark_node;
26754 	}
26755     }
26756 
26757   /* Check any placeholder constraints against the deduced type. */
26758   if (flag_concepts && !processing_template_decl)
26759     if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (auto_node))
26760       {
26761         /* Use the deduced type to check the associated constraints. If we
26762            have a partial-concept-id, rebuild the argument list so that
26763            we check using the extra arguments. */
26764         gcc_assert (TREE_CODE (constr) == CHECK_CONSTR);
26765         tree cargs = CHECK_CONSTR_ARGS (constr);
26766         if (TREE_VEC_LENGTH (cargs) > 1)
26767           {
26768             cargs = copy_node (cargs);
26769             TREE_VEC_ELT (cargs, 0) = TREE_VEC_ELT (targs, 0);
26770           }
26771         else
26772           cargs = targs;
26773         if (!constraints_satisfied_p (constr, cargs))
26774           {
26775             if (complain & tf_warning_or_error)
26776               {
26777                 switch (context)
26778                   {
26779                   case adc_unspecified:
26780 		  case adc_unify:
26781                     error("placeholder constraints not satisfied");
26782                     break;
26783                   case adc_variable_type:
26784 		  case adc_decomp_type:
26785                     error ("deduced initializer does not satisfy "
26786                            "placeholder constraints");
26787                     break;
26788                   case adc_return_type:
26789                     error ("deduced return type does not satisfy "
26790                            "placeholder constraints");
26791                     break;
26792                   case adc_requirement:
26793 		    error ("deduced expression type does not satisfy "
26794                            "placeholder constraints");
26795                     break;
26796                   }
26797                 diagnose_constraints (input_location, constr, targs);
26798               }
26799             return error_mark_node;
26800           }
26801       }
26802 
26803   if (processing_template_decl && context != adc_unify)
26804     outer_targs = current_template_args ();
26805   targs = add_to_template_args (outer_targs, targs);
26806   return tsubst (type, targs, complain, NULL_TREE);
26807 }
26808 
26809 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
26810    result.  */
26811 
26812 tree
26813 splice_late_return_type (tree type, tree late_return_type)
26814 {
26815   if (is_auto (type))
26816     {
26817       if (late_return_type)
26818 	return late_return_type;
26819 
26820       tree idx = get_template_parm_index (type);
26821       if (TEMPLATE_PARM_LEVEL (idx) <= processing_template_decl)
26822 	/* In an abbreviated function template we didn't know we were dealing
26823 	   with a function template when we saw the auto return type, so update
26824 	   it to have the correct level.  */
26825 	return make_auto_1 (TYPE_IDENTIFIER (type), true);
26826     }
26827   return type;
26828 }
26829 
26830 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
26831    'decltype(auto)' or a deduced class template.  */
26832 
26833 bool
26834 is_auto (const_tree type)
26835 {
26836   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
26837       && (TYPE_IDENTIFIER (type) == auto_identifier
26838 	  || TYPE_IDENTIFIER (type) == decltype_auto_identifier
26839 	  || CLASS_PLACEHOLDER_TEMPLATE (type)))
26840     return true;
26841   else
26842     return false;
26843 }
26844 
26845 /* for_each_template_parm callback for type_uses_auto.  */
26846 
26847 int
26848 is_auto_r (tree tp, void */*data*/)
26849 {
26850   return is_auto (tp);
26851 }
26852 
26853 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
26854    a use of `auto'.  Returns NULL_TREE otherwise.  */
26855 
26856 tree
26857 type_uses_auto (tree type)
26858 {
26859   if (type == NULL_TREE)
26860     return NULL_TREE;
26861   else if (flag_concepts)
26862     {
26863       /* The Concepts TS allows multiple autos in one type-specifier; just
26864 	 return the first one we find, do_auto_deduction will collect all of
26865 	 them.  */
26866       if (uses_template_parms (type))
26867 	return for_each_template_parm (type, is_auto_r, /*data*/NULL,
26868 				       /*visited*/NULL, /*nondeduced*/true);
26869       else
26870 	return NULL_TREE;
26871     }
26872   else
26873     return find_type_usage (type, is_auto);
26874 }
26875 
26876 /* Report ill-formed occurrences of auto types in ARGUMENTS.  If
26877    concepts are enabled, auto is acceptable in template arguments, but
26878    only when TEMPL identifies a template class.  Return TRUE if any
26879    such errors were reported.  */
26880 
26881 bool
26882 check_auto_in_tmpl_args (tree tmpl, tree args)
26883 {
26884   /* If there were previous errors, nevermind.  */
26885   if (!args || TREE_CODE (args) != TREE_VEC)
26886     return false;
26887 
26888   /* If TMPL is an identifier, we're parsing and we can't tell yet
26889      whether TMPL is supposed to be a type, a function or a variable.
26890      We'll only be able to tell during template substitution, so we
26891      expect to be called again then.  If concepts are enabled and we
26892      know we have a type, we're ok.  */
26893   if (flag_concepts
26894       && (identifier_p (tmpl)
26895 	  || (DECL_P (tmpl)
26896 	      &&  (DECL_TYPE_TEMPLATE_P (tmpl)
26897 		   || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)))))
26898     return false;
26899 
26900   /* Quickly search for any occurrences of auto; usually there won't
26901      be any, and then we'll avoid allocating the vector.  */
26902   if (!type_uses_auto (args))
26903     return false;
26904 
26905   bool errors = false;
26906 
26907   tree vec = extract_autos (args);
26908   for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
26909     {
26910       tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
26911       error_at (DECL_SOURCE_LOCATION (xauto),
26912 		"invalid use of %qT in template argument", xauto);
26913       errors = true;
26914     }
26915 
26916   return errors;
26917 }
26918 
26919 /* For a given template T, return the vector of typedefs referenced
26920    in T for which access check is needed at T instantiation time.
26921    T is either  a FUNCTION_DECL or a RECORD_TYPE.
26922    Those typedefs were added to T by the function
26923    append_type_to_template_for_access_check.  */
26924 
26925 vec<qualified_typedef_usage_t, va_gc> *
26926 get_types_needing_access_check (tree t)
26927 {
26928   tree ti;
26929   vec<qualified_typedef_usage_t, va_gc> *result = NULL;
26930 
26931   if (!t || t == error_mark_node)
26932     return NULL;
26933 
26934   if (!(ti = get_template_info (t)))
26935     return NULL;
26936 
26937   if (CLASS_TYPE_P (t)
26938       || TREE_CODE (t) == FUNCTION_DECL)
26939     {
26940       if (!TI_TEMPLATE (ti))
26941 	return NULL;
26942 
26943       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
26944     }
26945 
26946   return result;
26947 }
26948 
26949 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
26950    tied to T. That list of typedefs will be access checked at
26951    T instantiation time.
26952    T is either a FUNCTION_DECL or a RECORD_TYPE.
26953    TYPE_DECL is a TYPE_DECL node representing a typedef.
26954    SCOPE is the scope through which TYPE_DECL is accessed.
26955    LOCATION is the location of the usage point of TYPE_DECL.
26956 
26957    This function is a subroutine of
26958    append_type_to_template_for_access_check.  */
26959 
26960 static void
26961 append_type_to_template_for_access_check_1 (tree t,
26962 					    tree type_decl,
26963 					    tree scope,
26964 					    location_t location)
26965 {
26966   qualified_typedef_usage_t typedef_usage;
26967   tree ti;
26968 
26969   if (!t || t == error_mark_node)
26970     return;
26971 
26972   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
26973 	       || CLASS_TYPE_P (t))
26974 	      && type_decl
26975 	      && TREE_CODE (type_decl) == TYPE_DECL
26976 	      && scope);
26977 
26978   if (!(ti = get_template_info (t)))
26979     return;
26980 
26981   gcc_assert (TI_TEMPLATE (ti));
26982 
26983   typedef_usage.typedef_decl = type_decl;
26984   typedef_usage.context = scope;
26985   typedef_usage.locus = location;
26986 
26987   vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
26988 }
26989 
26990 /* Append TYPE_DECL to the template TEMPL.
26991    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
26992    At TEMPL instanciation time, TYPE_DECL will be checked to see
26993    if it can be accessed through SCOPE.
26994    LOCATION is the location of the usage point of TYPE_DECL.
26995 
26996    e.g. consider the following code snippet:
26997 
26998      class C
26999      {
27000        typedef int myint;
27001      };
27002 
27003      template<class U> struct S
27004      {
27005        C::myint mi; // <-- usage point of the typedef C::myint
27006      };
27007 
27008      S<char> s;
27009 
27010    At S<char> instantiation time, we need to check the access of C::myint
27011    In other words, we need to check the access of the myint typedef through
27012    the C scope. For that purpose, this function will add the myint typedef
27013    and the scope C through which its being accessed to a list of typedefs
27014    tied to the template S. That list will be walked at template instantiation
27015    time and access check performed on each typedefs it contains.
27016    Note that this particular code snippet should yield an error because
27017    myint is private to C.  */
27018 
27019 void
27020 append_type_to_template_for_access_check (tree templ,
27021                                           tree type_decl,
27022 					  tree scope,
27023 					  location_t location)
27024 {
27025   qualified_typedef_usage_t *iter;
27026   unsigned i;
27027 
27028   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
27029 
27030   /* Make sure we don't append the type to the template twice.  */
27031   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
27032     if (iter->typedef_decl == type_decl && scope == iter->context)
27033       return;
27034 
27035   append_type_to_template_for_access_check_1 (templ, type_decl,
27036 					      scope, location);
27037 }
27038 
27039 /* Convert the generic type parameters in PARM that match the types given in the
27040    range [START_IDX, END_IDX) from the current_template_parms into generic type
27041    packs.  */
27042 
27043 tree
27044 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
27045 {
27046   tree current = current_template_parms;
27047   int depth = TMPL_PARMS_DEPTH (current);
27048   current = INNERMOST_TEMPLATE_PARMS (current);
27049   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
27050 
27051   for (int i = 0; i < start_idx; ++i)
27052     TREE_VEC_ELT (replacement, i)
27053       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
27054 
27055   for (int i = start_idx; i < end_idx; ++i)
27056     {
27057       /* Create a distinct parameter pack type from the current parm and add it
27058 	 to the replacement args to tsubst below into the generic function
27059 	 parameter.  */
27060 
27061       tree o = TREE_TYPE (TREE_VALUE
27062 			  (TREE_VEC_ELT (current, i)));
27063       tree t = copy_type (o);
27064       TEMPLATE_TYPE_PARM_INDEX (t)
27065 	= reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
27066 				      o, 0, 0, tf_none);
27067       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
27068       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
27069       TYPE_MAIN_VARIANT (t) = t;
27070       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
27071       TYPE_CANONICAL (t) = canonical_type_parameter (t);
27072       TREE_VEC_ELT (replacement, i) = t;
27073       TREE_VALUE (TREE_VEC_ELT (current, i)) = TREE_CHAIN (t);
27074     }
27075 
27076   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
27077     TREE_VEC_ELT (replacement, i)
27078       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
27079 
27080   /* If there are more levels then build up the replacement with the outer
27081      template parms.  */
27082   if (depth > 1)
27083     replacement = add_to_template_args (template_parms_to_args
27084 					(TREE_CHAIN (current_template_parms)),
27085 					replacement);
27086 
27087   return tsubst (parm, replacement, tf_none, NULL_TREE);
27088 }
27089 
27090 /* Entries in the decl_constraint hash table. */
27091 struct GTY((for_user)) constr_entry
27092 {
27093   tree decl;
27094   tree ci;
27095 };
27096 
27097 /* Hashing function and equality for constraint entries. */
27098 struct constr_hasher : ggc_ptr_hash<constr_entry>
27099 {
27100   static hashval_t hash (constr_entry *e)
27101   {
27102     return (hashval_t)DECL_UID (e->decl);
27103   }
27104 
27105   static bool equal (constr_entry *e1, constr_entry *e2)
27106   {
27107     return e1->decl == e2->decl;
27108   }
27109 };
27110 
27111 /* A mapping from declarations to constraint information. Note that
27112    both templates and their underlying declarations are mapped to the
27113    same constraint information.
27114 
27115    FIXME: This is defined in pt.c because garbage collection
27116    code is not being generated for constraint.cc. */
27117 
27118 static GTY (()) hash_table<constr_hasher> *decl_constraints;
27119 
27120 /* Returns the template constraints of declaration T. If T is not
27121    constrained, return NULL_TREE. Note that T must be non-null. */
27122 
27123 tree
27124 get_constraints (tree t)
27125 {
27126   if (!flag_concepts)
27127     return NULL_TREE;
27128 
27129   gcc_assert (DECL_P (t));
27130   if (TREE_CODE (t) == TEMPLATE_DECL)
27131     t = DECL_TEMPLATE_RESULT (t);
27132   constr_entry elt = { t, NULL_TREE };
27133   constr_entry* found = decl_constraints->find (&elt);
27134   if (found)
27135     return found->ci;
27136   else
27137     return NULL_TREE;
27138 }
27139 
27140 /* Associate the given constraint information CI with the declaration
27141    T. If T is a template, then the constraints are associated with
27142    its underlying declaration. Don't build associations if CI is
27143    NULL_TREE.  */
27144 
27145 void
27146 set_constraints (tree t, tree ci)
27147 {
27148   if (!ci)
27149     return;
27150   gcc_assert (t && flag_concepts);
27151   if (TREE_CODE (t) == TEMPLATE_DECL)
27152     t = DECL_TEMPLATE_RESULT (t);
27153   gcc_assert (!get_constraints (t));
27154   constr_entry elt = {t, ci};
27155   constr_entry** slot = decl_constraints->find_slot (&elt, INSERT);
27156   constr_entry* entry = ggc_alloc<constr_entry> ();
27157   *entry = elt;
27158   *slot = entry;
27159 }
27160 
27161 /* Remove the associated constraints of the declaration T.  */
27162 
27163 void
27164 remove_constraints (tree t)
27165 {
27166   gcc_assert (DECL_P (t));
27167   if (TREE_CODE (t) == TEMPLATE_DECL)
27168     t = DECL_TEMPLATE_RESULT (t);
27169 
27170   constr_entry elt = {t, NULL_TREE};
27171   constr_entry** slot = decl_constraints->find_slot (&elt, NO_INSERT);
27172   if (slot)
27173     decl_constraints->clear_slot (slot);
27174 }
27175 
27176 /* Memoized satisfaction results for declarations. This
27177    maps the pair (constraint_info, arguments) to the result computed
27178    by constraints_satisfied_p.  */
27179 
27180 struct GTY((for_user)) constraint_sat_entry
27181 {
27182   tree ci;
27183   tree args;
27184   tree result;
27185 };
27186 
27187 /* Hashing function and equality for constraint entries. */
27188 
27189 struct constraint_sat_hasher : ggc_ptr_hash<constraint_sat_entry>
27190 {
27191   static hashval_t hash (constraint_sat_entry *e)
27192   {
27193     hashval_t val = iterative_hash_object(e->ci, 0);
27194     return iterative_hash_template_arg (e->args, val);
27195   }
27196 
27197   static bool equal (constraint_sat_entry *e1, constraint_sat_entry *e2)
27198   {
27199     return e1->ci == e2->ci && comp_template_args (e1->args, e2->args);
27200   }
27201 };
27202 
27203 /* Memoized satisfaction results for concept checks. */
27204 
27205 struct GTY((for_user)) concept_spec_entry
27206 {
27207   tree tmpl;
27208   tree args;
27209   tree result;
27210 };
27211 
27212 /* Hashing function and equality for constraint entries.  */
27213 
27214 struct concept_spec_hasher : ggc_ptr_hash<concept_spec_entry>
27215 {
27216   static hashval_t hash (concept_spec_entry *e)
27217   {
27218     return hash_tmpl_and_args (e->tmpl, e->args);
27219   }
27220 
27221   static bool equal (concept_spec_entry *e1, concept_spec_entry *e2)
27222   {
27223     ++comparing_specializations;
27224     bool eq = e1->tmpl == e2->tmpl && comp_template_args (e1->args, e2->args);
27225     --comparing_specializations;
27226     return eq;
27227   }
27228 };
27229 
27230 static GTY (()) hash_table<constraint_sat_hasher> *constraint_memos;
27231 static GTY (()) hash_table<concept_spec_hasher> *concept_memos;
27232 
27233 /* Search for a memoized satisfaction result. Returns one of the
27234    truth value nodes if previously memoized, or NULL_TREE otherwise.   */
27235 
27236 tree
27237 lookup_constraint_satisfaction (tree ci, tree args)
27238 {
27239   constraint_sat_entry elt = { ci, args, NULL_TREE };
27240   constraint_sat_entry* found = constraint_memos->find (&elt);
27241   if (found)
27242     return found->result;
27243   else
27244     return NULL_TREE;
27245 }
27246 
27247 /* Memoize the result of a satisfication test. Returns the saved result.  */
27248 
27249 tree
27250 memoize_constraint_satisfaction (tree ci, tree args, tree result)
27251 {
27252   constraint_sat_entry elt = {ci, args, result};
27253   constraint_sat_entry** slot = constraint_memos->find_slot (&elt, INSERT);
27254   constraint_sat_entry* entry = ggc_alloc<constraint_sat_entry> ();
27255   *entry = elt;
27256   *slot = entry;
27257   return result;
27258 }
27259 
27260 /* Search for a memoized satisfaction result for a concept. */
27261 
27262 tree
27263 lookup_concept_satisfaction (tree tmpl, tree args)
27264 {
27265   concept_spec_entry elt = { tmpl, args, NULL_TREE };
27266   concept_spec_entry* found = concept_memos->find (&elt);
27267   if (found)
27268     return found->result;
27269   else
27270     return NULL_TREE;
27271 }
27272 
27273 /* Memoize the result of a concept check. Returns the saved result.  */
27274 
27275 tree
27276 memoize_concept_satisfaction (tree tmpl, tree args, tree result)
27277 {
27278   concept_spec_entry elt = {tmpl, args, result};
27279   concept_spec_entry** slot = concept_memos->find_slot (&elt, INSERT);
27280   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
27281   *entry = elt;
27282   *slot = entry;
27283   return result;
27284 }
27285 
27286 static GTY (()) hash_table<concept_spec_hasher> *concept_expansions;
27287 
27288 /* Returns a prior concept specialization. This returns the substituted
27289    and normalized constraints defined by the concept.  */
27290 
27291 tree
27292 get_concept_expansion (tree tmpl, tree args)
27293 {
27294   concept_spec_entry elt = { tmpl, args, NULL_TREE };
27295   concept_spec_entry* found = concept_expansions->find (&elt);
27296   if (found)
27297     return found->result;
27298   else
27299     return NULL_TREE;
27300 }
27301 
27302 /* Save a concept expansion for later.  */
27303 
27304 tree
27305 save_concept_expansion (tree tmpl, tree args, tree def)
27306 {
27307   concept_spec_entry elt = {tmpl, args, def};
27308   concept_spec_entry** slot = concept_expansions->find_slot (&elt, INSERT);
27309   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
27310   *entry = elt;
27311   *slot = entry;
27312   return def;
27313 }
27314 
27315 static hashval_t
27316 hash_subsumption_args (tree t1, tree t2)
27317 {
27318   gcc_assert (TREE_CODE (t1) == CHECK_CONSTR);
27319   gcc_assert (TREE_CODE (t2) == CHECK_CONSTR);
27320   int val = 0;
27321   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t1), val);
27322   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t1), val);
27323   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t2), val);
27324   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t2), val);
27325   return val;
27326 }
27327 
27328 /* Compare the constraints of two subsumption entries.  The LEFT1 and
27329    LEFT2 arguments comprise the first subsumption pair and the RIGHT1
27330    and RIGHT2 arguments comprise the second. These are all CHECK_CONSTRs. */
27331 
27332 static bool
27333 comp_subsumption_args (tree left1, tree left2, tree right1, tree right2)
27334 {
27335   if (CHECK_CONSTR_CONCEPT (left1) == CHECK_CONSTR_CONCEPT (right1))
27336     if (CHECK_CONSTR_CONCEPT (left2) == CHECK_CONSTR_CONCEPT (right2))
27337       if (comp_template_args (CHECK_CONSTR_ARGS (left1),
27338                              CHECK_CONSTR_ARGS (right1)))
27339         return comp_template_args (CHECK_CONSTR_ARGS (left2),
27340                                   CHECK_CONSTR_ARGS (right2));
27341   return false;
27342 }
27343 
27344 /* Key/value pair for learning and memoizing subsumption results. This
27345    associates a pair of check constraints (including arguments) with
27346    a boolean value indicating the result.  */
27347 
27348 struct GTY((for_user)) subsumption_entry
27349 {
27350   tree t1;
27351   tree t2;
27352   bool result;
27353 };
27354 
27355 /* Hashing function and equality for constraint entries.  */
27356 
27357 struct subsumption_hasher : ggc_ptr_hash<subsumption_entry>
27358 {
27359   static hashval_t hash (subsumption_entry *e)
27360   {
27361     return hash_subsumption_args (e->t1, e->t2);
27362   }
27363 
27364   static bool equal (subsumption_entry *e1, subsumption_entry *e2)
27365   {
27366     ++comparing_specializations;
27367     bool eq = comp_subsumption_args(e1->t1, e1->t2, e2->t1, e2->t2);
27368     --comparing_specializations;
27369     return eq;
27370   }
27371 };
27372 
27373 static GTY (()) hash_table<subsumption_hasher> *subsumption_table;
27374 
27375 /* Search for a previously cached subsumption result. */
27376 
27377 bool*
27378 lookup_subsumption_result (tree t1, tree t2)
27379 {
27380   subsumption_entry elt = { t1, t2, false };
27381   subsumption_entry* found = subsumption_table->find (&elt);
27382   if (found)
27383     return &found->result;
27384   else
27385     return 0;
27386 }
27387 
27388 /* Save a subsumption result. */
27389 
27390 bool
27391 save_subsumption_result (tree t1, tree t2, bool result)
27392 {
27393   subsumption_entry elt = {t1, t2, result};
27394   subsumption_entry** slot = subsumption_table->find_slot (&elt, INSERT);
27395   subsumption_entry* entry = ggc_alloc<subsumption_entry> ();
27396   *entry = elt;
27397   *slot = entry;
27398   return result;
27399 }
27400 
27401 /* Set up the hash table for constraint association. */
27402 
27403 void
27404 init_constraint_processing (void)
27405 {
27406   if (!flag_concepts)
27407     return;
27408 
27409   decl_constraints = hash_table<constr_hasher>::create_ggc(37);
27410   constraint_memos = hash_table<constraint_sat_hasher>::create_ggc(37);
27411   concept_memos = hash_table<concept_spec_hasher>::create_ggc(37);
27412   concept_expansions = hash_table<concept_spec_hasher>::create_ggc(37);
27413   subsumption_table = hash_table<subsumption_hasher>::create_ggc(37);
27414 }
27415 
27416 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
27417    0..N-1.  */
27418 
27419 void
27420 declare_integer_pack (void)
27421 {
27422   tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
27423 			       build_function_type_list (integer_type_node,
27424 							 integer_type_node,
27425 							 NULL_TREE),
27426 			       NULL_TREE, ECF_CONST);
27427   DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
27428   DECL_BUILT_IN_CLASS (ipfn) = BUILT_IN_FRONTEND;
27429 }
27430 
27431 /* Set up the hash tables for template instantiations.  */
27432 
27433 void
27434 init_template_processing (void)
27435 {
27436   decl_specializations = hash_table<spec_hasher>::create_ggc (37);
27437   type_specializations = hash_table<spec_hasher>::create_ggc (37);
27438 
27439   if (cxx_dialect >= cxx11)
27440     declare_integer_pack ();
27441 }
27442 
27443 /* Print stats about the template hash tables for -fstats.  */
27444 
27445 void
27446 print_template_statistics (void)
27447 {
27448   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
27449 	   "%f collisions\n", (long) decl_specializations->size (),
27450 	   (long) decl_specializations->elements (),
27451 	   decl_specializations->collisions ());
27452   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
27453 	   "%f collisions\n", (long) type_specializations->size (),
27454 	   (long) type_specializations->elements (),
27455 	   type_specializations->collisions ());
27456 }
27457 
27458 #if CHECKING_P
27459 
27460 namespace selftest {
27461 
27462 /* Verify that build_non_dependent_expr () works, for various expressions,
27463    and that location wrappers don't affect the results.  */
27464 
27465 static void
27466 test_build_non_dependent_expr ()
27467 {
27468   location_t loc = BUILTINS_LOCATION;
27469 
27470   /* Verify constants, without and with location wrappers.  */
27471   tree int_cst = build_int_cst (integer_type_node, 42);
27472   ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
27473 
27474   tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
27475   ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
27476   ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
27477 
27478   tree string_lit = build_string (4, "foo");
27479   TREE_TYPE (string_lit) = char_array_type_node;
27480   string_lit = fix_string_type (string_lit);
27481   ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
27482 
27483   tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
27484   ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
27485   ASSERT_EQ (wrapped_string_lit,
27486 	     build_non_dependent_expr (wrapped_string_lit));
27487 }
27488 
27489 /* Verify that type_dependent_expression_p () works correctly, even
27490    in the presence of location wrapper nodes.  */
27491 
27492 static void
27493 test_type_dependent_expression_p ()
27494 {
27495   location_t loc = BUILTINS_LOCATION;
27496 
27497   tree name = get_identifier ("foo");
27498 
27499   /* If no templates are involved, nothing is type-dependent.  */
27500   gcc_assert (!processing_template_decl);
27501   ASSERT_FALSE (type_dependent_expression_p (name));
27502 
27503   ++processing_template_decl;
27504 
27505   /* Within a template, an unresolved name is always type-dependent.  */
27506   ASSERT_TRUE (type_dependent_expression_p (name));
27507 
27508   /* Ensure it copes with NULL_TREE and errors.  */
27509   ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
27510   ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
27511 
27512   /* A USING_DECL in a template should be type-dependent, even if wrapped
27513      with a location wrapper (PR c++/83799).  */
27514   tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
27515   TREE_TYPE (using_decl) = integer_type_node;
27516   ASSERT_TRUE (type_dependent_expression_p (using_decl));
27517   tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
27518   ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
27519   ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
27520 
27521   --processing_template_decl;
27522 }
27523 
27524 /* Run all of the selftests within this file.  */
27525 
27526 void
27527 cp_pt_c_tests ()
27528 {
27529   test_build_non_dependent_expr ();
27530   test_type_dependent_expression_p ();
27531 }
27532 
27533 } // namespace selftest
27534 
27535 #endif /* #if CHECKING_P */
27536 
27537 #include "gt-cp-pt.h"
27538