1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2    Copyright (C) 1992-2020 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 #include "target.h"
46 
47 /* The type of functions taking a tree, and some additional data, and
48    returning an int.  */
49 typedef int (*tree_fn_t) (tree, void*);
50 
51 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
52    instantiations have been deferred, either because their definitions
53    were not yet available, or because we were putting off doing the work.  */
54 struct GTY ((chain_next ("%h.next"))) pending_template
55 {
56   struct pending_template *next;
57   struct tinst_level *tinst;
58 };
59 
60 static GTY(()) struct pending_template *pending_templates;
61 static GTY(()) struct pending_template *last_pending_template;
62 
63 int processing_template_parmlist;
64 static int template_header_count;
65 
66 static vec<int> inline_parm_levels;
67 
68 static GTY(()) struct tinst_level *current_tinst_level;
69 
70 static GTY(()) vec<tree, va_gc> *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.
local_specialization_stack(lss_policy policy)82 local_specialization_stack::local_specialization_stack (lss_policy policy)
83   : saved (local_specializations)
84 {
85   if (policy == lss_nop)
86     ;
87   else if (policy == lss_blank || !saved)
88     local_specializations = new hash_map<tree, tree>;
89   else
90     local_specializations = new hash_map<tree, tree>(*saved);
91 }
92 
~local_specialization_stack()93 local_specialization_stack::~local_specialization_stack ()
94 {
95   if (local_specializations != saved)
96     {
97       delete local_specializations;
98       local_specializations = saved;
99     }
100 }
101 
102 /* True if we've recursed into fn_type_unification too many times.  */
103 static bool excessive_deduction_depth;
104 
105 struct GTY((for_user)) spec_entry
106 {
107   tree tmpl;
108   tree args;
109   tree spec;
110 };
111 
112 struct spec_hasher : ggc_ptr_hash<spec_entry>
113 {
114   static hashval_t hash (spec_entry *);
115   static bool equal (spec_entry *, spec_entry *);
116 };
117 
118 static GTY (()) hash_table<spec_hasher> *decl_specializations;
119 
120 static GTY (()) hash_table<spec_hasher> *type_specializations;
121 
122 /* Contains canonical template parameter types. The vector is indexed by
123    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
124    TREE_LIST, whose TREE_VALUEs contain the canonical template
125    parameters of various types and levels.  */
126 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
127 
128 #define UNIFY_ALLOW_NONE 0
129 #define UNIFY_ALLOW_MORE_CV_QUAL 1
130 #define UNIFY_ALLOW_LESS_CV_QUAL 2
131 #define UNIFY_ALLOW_DERIVED 4
132 #define UNIFY_ALLOW_INTEGER 8
133 #define UNIFY_ALLOW_OUTER_LEVEL 16
134 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
135 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
136 
137 enum template_base_result {
138   tbr_incomplete_type,
139   tbr_ambiguous_baseclass,
140   tbr_success
141 };
142 
143 static bool resolve_overloaded_unification (tree, tree, tree, tree,
144 					    unification_kind_t, int,
145 					    bool);
146 static int try_one_overload (tree, tree, tree, tree, tree,
147 			     unification_kind_t, int, bool, bool);
148 static int unify (tree, tree, tree, tree, int, bool);
149 static void add_pending_template (tree);
150 static tree reopen_tinst_level (struct tinst_level *);
151 static tree tsubst_initializer_list (tree, tree);
152 static tree get_partial_spec_bindings (tree, tree, tree);
153 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
154 				   bool, bool);
155 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
156 					      bool, bool);
157 static void tsubst_enum	(tree, tree, tree);
158 static tree add_to_template_args (tree, tree);
159 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
160 static int check_non_deducible_conversion (tree, tree, int, int,
161 					   struct conversion **, bool);
162 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
163 					     tree);
164 static int type_unification_real (tree, tree, tree, const tree *,
165 				  unsigned int, int, unification_kind_t,
166 				  vec<deferred_access_check, va_gc> **,
167 				  bool);
168 static void note_template_header (int);
169 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
170 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
171 static tree convert_template_argument (tree, tree, tree,
172 				       tsubst_flags_t, int, tree);
173 static tree for_each_template_parm (tree, tree_fn_t, void*,
174 				    hash_set<tree> *, bool, tree_fn_t = NULL);
175 static tree expand_template_argument_pack (tree);
176 static tree build_template_parm_index (int, int, int, tree, tree);
177 static bool inline_needs_template_parms (tree, bool);
178 static void push_inline_template_parms_recursive (tree, int);
179 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
180 static int mark_template_parm (tree, void *);
181 static int template_parm_this_level_p (tree, void *);
182 static tree tsubst_friend_function (tree, tree);
183 static tree tsubst_friend_class (tree, tree);
184 static int can_complete_type_without_circularity (tree);
185 static tree get_bindings (tree, tree, tree, bool);
186 static int template_decl_level (tree);
187 static int check_cv_quals_for_unify (int, tree, tree);
188 static int unify_pack_expansion (tree, tree, tree,
189 				 tree, unification_kind_t, bool, bool);
190 static tree copy_template_args (tree);
191 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
192 tree most_specialized_partial_spec (tree, tsubst_flags_t);
193 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
194 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
195 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
196 static bool check_specialization_scope (void);
197 static tree process_partial_specialization (tree);
198 static void set_current_access_from_decl (tree);
199 static enum template_base_result get_template_base (tree, tree, tree, tree,
200 						    bool , tree *);
201 static tree try_class_unification (tree, tree, tree, tree, bool);
202 static bool class_nttp_const_wrapper_p (tree t);
203 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
204 					   tree, tree);
205 static bool template_template_parm_bindings_ok_p (tree, tree);
206 static void tsubst_default_arguments (tree, tsubst_flags_t);
207 static tree for_each_template_parm_r (tree *, int *, void *);
208 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
209 static void copy_default_args_to_explicit_spec (tree);
210 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
211 static bool dependent_template_arg_p (tree);
212 static bool any_template_arguments_need_structural_equality_p (tree);
213 static bool dependent_type_p_r (tree);
214 static tree tsubst_copy	(tree, tree, tsubst_flags_t, tree);
215 static tree tsubst_decl (tree, tree, tsubst_flags_t);
216 static void perform_typedefs_access_check (tree tmpl, tree targs);
217 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
218 							location_t);
219 static tree listify (tree);
220 static tree listify_autos (tree, tree);
221 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
222 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
223 static bool complex_alias_template_p (const_tree tmpl);
224 static tree get_underlying_template (tree);
225 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
226 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
227 static tree make_argument_pack (tree);
228 static void register_parameter_specializations (tree, tree);
229 static tree enclosing_instantiation_of (tree tctx);
230 
231 /* Make the current scope suitable for access checking when we are
232    processing T.  T can be FUNCTION_DECL for instantiated function
233    template, VAR_DECL for static member variable, or TYPE_DECL for
234    alias template (needed by instantiate_decl).  */
235 
236 void
push_access_scope(tree t)237 push_access_scope (tree t)
238 {
239   gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
240 	      || TREE_CODE (t) == TYPE_DECL);
241 
242   if (DECL_FRIEND_CONTEXT (t))
243     push_nested_class (DECL_FRIEND_CONTEXT (t));
244   else if (DECL_CLASS_SCOPE_P (t))
245     push_nested_class (DECL_CONTEXT (t));
246   else
247     push_to_top_level ();
248 
249   if (TREE_CODE (t) == FUNCTION_DECL)
250     {
251       vec_safe_push (saved_access_scope, current_function_decl);
252       current_function_decl = t;
253     }
254 }
255 
256 /* Restore the scope set up by push_access_scope.  T is the node we
257    are processing.  */
258 
259 void
pop_access_scope(tree t)260 pop_access_scope (tree t)
261 {
262   if (TREE_CODE (t) == FUNCTION_DECL)
263     current_function_decl = saved_access_scope->pop();
264 
265   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
266     pop_nested_class ();
267   else
268     pop_from_top_level ();
269 }
270 
271 /* Do any processing required when DECL (a member template
272    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
273    to DECL, unless it is a specialization, in which case the DECL
274    itself is returned.  */
275 
276 tree
finish_member_template_decl(tree decl)277 finish_member_template_decl (tree decl)
278 {
279   if (decl == error_mark_node)
280     return error_mark_node;
281 
282   gcc_assert (DECL_P (decl));
283 
284   if (TREE_CODE (decl) == TYPE_DECL)
285     {
286       tree type;
287 
288       type = TREE_TYPE (decl);
289       if (type == error_mark_node)
290 	return error_mark_node;
291       if (MAYBE_CLASS_TYPE_P (type)
292 	  && CLASSTYPE_TEMPLATE_INFO (type)
293 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
294 	{
295 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
296 	  check_member_template (tmpl);
297 	  return tmpl;
298 	}
299       return NULL_TREE;
300     }
301   else if (TREE_CODE (decl) == FIELD_DECL)
302     error_at (DECL_SOURCE_LOCATION (decl),
303 	      "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_at (DECL_SOURCE_LOCATION (decl),
316 	      "invalid member template declaration %qD", decl);
317 
318   return error_mark_node;
319 }
320 
321 /* Create a template info node.  */
322 
323 tree
build_template_info(tree template_decl,tree template_args)324 build_template_info (tree template_decl, tree template_args)
325 {
326   tree result = make_node (TEMPLATE_INFO);
327   TI_TEMPLATE (result) = template_decl;
328   TI_ARGS (result) = template_args;
329   return result;
330 }
331 
332 /* Return the template info node corresponding to T, whatever T is.  */
333 
334 tree
get_template_info(const_tree t)335 get_template_info (const_tree t)
336 {
337   tree tinfo = NULL_TREE;
338 
339   if (!t || t == error_mark_node)
340     return NULL;
341 
342   if (TREE_CODE (t) == NAMESPACE_DECL
343       || TREE_CODE (t) == PARM_DECL)
344     return NULL;
345 
346   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
347     tinfo = DECL_TEMPLATE_INFO (t);
348 
349   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
350     t = TREE_TYPE (t);
351 
352   if (OVERLOAD_TYPE_P (t))
353     tinfo = TYPE_TEMPLATE_INFO (t);
354   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
355     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
356 
357   return tinfo;
358 }
359 
360 /* Returns the template nesting level of the indicated class TYPE.
361 
362    For example, in:
363      template <class T>
364      struct A
365      {
366        template <class U>
367        struct B {};
368      };
369 
370    A<T>::B<U> has depth two, while A<T> has depth one.
371    Both A<T>::B<int> and A<int>::B<U> have depth one, if
372    they are instantiations, not specializations.
373 
374    This function is guaranteed to return 0 if passed NULL_TREE so
375    that, for example, `template_class_depth (current_class_type)' is
376    always safe.  */
377 
378 int
template_class_depth(tree type)379 template_class_depth (tree type)
380 {
381   int depth;
382 
383   for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
384     {
385       tree tinfo = get_template_info (type);
386 
387       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
388 	  && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
389 	++depth;
390 
391       if (DECL_P (type))
392 	{
393 	  if (tree fctx = DECL_FRIEND_CONTEXT (type))
394 	    type = fctx;
395 	  else
396 	    type = CP_DECL_CONTEXT (type);
397 	}
398       else if (LAMBDA_TYPE_P (type) && LAMBDA_TYPE_EXTRA_SCOPE (type))
399 	type = LAMBDA_TYPE_EXTRA_SCOPE (type);
400       else
401 	type = CP_TYPE_CONTEXT (type);
402     }
403 
404   return depth;
405 }
406 
407 /* Return TRUE if NODE instantiates a template that has arguments of
408    its own, be it directly a primary template or indirectly through a
409    partial specializations.  */
410 static bool
instantiates_primary_template_p(tree node)411 instantiates_primary_template_p (tree node)
412 {
413   tree tinfo = get_template_info (node);
414   if (!tinfo)
415     return false;
416 
417   tree tmpl = TI_TEMPLATE (tinfo);
418   if (PRIMARY_TEMPLATE_P (tmpl))
419     return true;
420 
421   if (!DECL_TEMPLATE_SPECIALIZATION (tmpl))
422     return false;
423 
424   /* So now we know we have a specialization, but it could be a full
425      or a partial specialization.  To tell which, compare the depth of
426      its template arguments with those of its context.  */
427 
428   tree ctxt = DECL_CONTEXT (tmpl);
429   tree ctinfo = get_template_info (ctxt);
430   if (!ctinfo)
431     return true;
432 
433   return (TMPL_ARGS_DEPTH (TI_ARGS (tinfo))
434 	  > TMPL_ARGS_DEPTH (TI_ARGS (ctinfo)));
435 }
436 
437 /* Subroutine of maybe_begin_member_template_processing.
438    Returns true if processing DECL needs us to push template parms.  */
439 
440 static bool
inline_needs_template_parms(tree decl,bool nsdmi)441 inline_needs_template_parms (tree decl, bool nsdmi)
442 {
443   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
444     return false;
445 
446   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
447 	  > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
448 }
449 
450 /* Subroutine of maybe_begin_member_template_processing.
451    Push the template parms in PARMS, starting from LEVELS steps into the
452    chain, and ending at the beginning, since template parms are listed
453    innermost first.  */
454 
455 static void
push_inline_template_parms_recursive(tree parmlist,int levels)456 push_inline_template_parms_recursive (tree parmlist, int levels)
457 {
458   tree parms = TREE_VALUE (parmlist);
459   int i;
460 
461   if (levels > 1)
462     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
463 
464   ++processing_template_decl;
465   current_template_parms
466     = tree_cons (size_int (processing_template_decl),
467 		 parms, current_template_parms);
468   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
469 
470   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
471 	       NULL);
472   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
473     {
474       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
475 
476       if (error_operand_p (parm))
477 	continue;
478 
479       gcc_assert (DECL_P (parm));
480 
481       switch (TREE_CODE (parm))
482 	{
483 	case TYPE_DECL:
484 	case TEMPLATE_DECL:
485 	  pushdecl (parm);
486 	  break;
487 
488 	case PARM_DECL:
489 	  /* Push the CONST_DECL.  */
490 	  pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
491 	  break;
492 
493 	default:
494 	  gcc_unreachable ();
495 	}
496     }
497 }
498 
499 /* Restore the template parameter context for a member template, a
500    friend template defined in a class definition, or a non-template
501    member of template class.  */
502 
503 void
maybe_begin_member_template_processing(tree decl)504 maybe_begin_member_template_processing (tree decl)
505 {
506   tree parms;
507   int levels = 0;
508   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
509 
510   if (nsdmi)
511     {
512       tree ctx = DECL_CONTEXT (decl);
513       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
514 	      /* Disregard full specializations (c++/60999).  */
515 	      && uses_template_parms (ctx)
516 	      ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
517     }
518 
519   if (inline_needs_template_parms (decl, nsdmi))
520     {
521       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
522       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
523 
524       if (DECL_TEMPLATE_SPECIALIZATION (decl))
525 	{
526 	  --levels;
527 	  parms = TREE_CHAIN (parms);
528 	}
529 
530       push_inline_template_parms_recursive (parms, levels);
531     }
532 
533   /* Remember how many levels of template parameters we pushed so that
534      we can pop them later.  */
535   inline_parm_levels.safe_push (levels);
536 }
537 
538 /* Undo the effects of maybe_begin_member_template_processing.  */
539 
540 void
maybe_end_member_template_processing(void)541 maybe_end_member_template_processing (void)
542 {
543   int i;
544   int last;
545 
546   if (inline_parm_levels.length () == 0)
547     return;
548 
549   last = inline_parm_levels.pop ();
550   for (i = 0; i < last; ++i)
551     {
552       --processing_template_decl;
553       current_template_parms = TREE_CHAIN (current_template_parms);
554       poplevel (0, 0, 0);
555     }
556 }
557 
558 /* Return a new template argument vector which contains all of ARGS,
559    but has as its innermost set of arguments the EXTRA_ARGS.  */
560 
561 static tree
add_to_template_args(tree args,tree extra_args)562 add_to_template_args (tree args, tree extra_args)
563 {
564   tree new_args;
565   int extra_depth;
566   int i;
567   int j;
568 
569   if (args == NULL_TREE || extra_args == error_mark_node)
570     return extra_args;
571 
572   extra_depth = TMPL_ARGS_DEPTH (extra_args);
573   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
574 
575   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
576     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
577 
578   for (j = 1; j <= extra_depth; ++j, ++i)
579     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
580 
581   return new_args;
582 }
583 
584 /* Like add_to_template_args, but only the outermost ARGS are added to
585    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
586    (EXTRA_ARGS) levels are added.  This function is used to combine
587    the template arguments from a partial instantiation with the
588    template arguments used to attain the full instantiation from the
589    partial instantiation.  */
590 
591 tree
add_outermost_template_args(tree args,tree extra_args)592 add_outermost_template_args (tree args, tree extra_args)
593 {
594   tree new_args;
595 
596   /* If there are more levels of EXTRA_ARGS than there are ARGS,
597      something very fishy is going on.  */
598   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
599 
600   /* If *all* the new arguments will be the EXTRA_ARGS, just return
601      them.  */
602   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
603     return extra_args;
604 
605   /* For the moment, we make ARGS look like it contains fewer levels.  */
606   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
607 
608   new_args = add_to_template_args (args, extra_args);
609 
610   /* Now, we restore ARGS to its full dimensions.  */
611   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
612 
613   return new_args;
614 }
615 
616 /* Return the N levels of innermost template arguments from the ARGS.  */
617 
618 tree
get_innermost_template_args(tree args,int n)619 get_innermost_template_args (tree args, int n)
620 {
621   tree new_args;
622   int extra_levels;
623   int i;
624 
625   gcc_assert (n >= 0);
626 
627   /* If N is 1, just return the innermost set of template arguments.  */
628   if (n == 1)
629     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
630 
631   /* If we're not removing anything, just return the arguments we were
632      given.  */
633   extra_levels = TMPL_ARGS_DEPTH (args) - n;
634   gcc_assert (extra_levels >= 0);
635   if (extra_levels == 0)
636     return args;
637 
638   /* Make a new set of arguments, not containing the outer arguments.  */
639   new_args = make_tree_vec (n);
640   for (i = 1; i <= n; ++i)
641     SET_TMPL_ARGS_LEVEL (new_args, i,
642 			 TMPL_ARGS_LEVEL (args, i + extra_levels));
643 
644   return new_args;
645 }
646 
647 /* The inverse of get_innermost_template_args: Return all but the innermost
648    EXTRA_LEVELS levels of template arguments from the ARGS.  */
649 
650 static tree
strip_innermost_template_args(tree args,int extra_levels)651 strip_innermost_template_args (tree args, int extra_levels)
652 {
653   tree new_args;
654   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
655   int i;
656 
657   gcc_assert (n >= 0);
658 
659   /* If N is 1, just return the outermost set of template arguments.  */
660   if (n == 1)
661     return TMPL_ARGS_LEVEL (args, 1);
662 
663   /* If we're not removing anything, just return the arguments we were
664      given.  */
665   gcc_assert (extra_levels >= 0);
666   if (extra_levels == 0)
667     return args;
668 
669   /* Make a new set of arguments, not containing the inner arguments.  */
670   new_args = make_tree_vec (n);
671   for (i = 1; i <= n; ++i)
672     SET_TMPL_ARGS_LEVEL (new_args, i,
673 			 TMPL_ARGS_LEVEL (args, i));
674 
675   return new_args;
676 }
677 
678 /* We've got a template header coming up; push to a new level for storing
679    the parms.  */
680 
681 void
begin_template_parm_list(void)682 begin_template_parm_list (void)
683 {
684   /* We use a non-tag-transparent scope here, which causes pushtag to
685      put tags in this scope, rather than in the enclosing class or
686      namespace scope.  This is the right thing, since we want
687      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
688      global template class, push_template_decl handles putting the
689      TEMPLATE_DECL into top-level scope.  For a nested template class,
690      e.g.:
691 
692        template <class T> struct S1 {
693 	 template <class T> struct S2 {};
694        };
695 
696      pushtag contains special code to insert the TEMPLATE_DECL for S2
697      at the right scope.  */
698   begin_scope (sk_template_parms, NULL);
699   ++processing_template_decl;
700   ++processing_template_parmlist;
701   note_template_header (0);
702 
703   /* Add a dummy parameter level while we process the parameter list.  */
704   current_template_parms
705     = tree_cons (size_int (processing_template_decl),
706 		 make_tree_vec (0),
707 		 current_template_parms);
708 }
709 
710 /* This routine is called when a specialization is declared.  If it is
711    invalid to declare a specialization here, an error is reported and
712    false is returned, otherwise this routine will return true.  */
713 
714 static bool
check_specialization_scope(void)715 check_specialization_scope (void)
716 {
717   tree scope = current_scope ();
718 
719   /* [temp.expl.spec]
720 
721      An explicit specialization shall be declared in the namespace of
722      which the template is a member, or, for member templates, in the
723      namespace of which the enclosing class or enclosing class
724      template is a member.  An explicit specialization of a member
725      function, member class or static data member of a class template
726      shall be declared in the namespace of which the class template
727      is a member.  */
728   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
729     {
730       error ("explicit specialization in non-namespace scope %qD", scope);
731       return false;
732     }
733 
734   /* [temp.expl.spec]
735 
736      In an explicit specialization declaration for a member of a class
737      template or a member template that appears in namespace scope,
738      the member template and some of its enclosing class templates may
739      remain unspecialized, except that the declaration shall not
740      explicitly specialize a class member template if its enclosing
741      class templates are not explicitly specialized as well.  */
742   if (current_template_parms)
743     {
744       error ("enclosing class templates are not explicitly specialized");
745       return false;
746     }
747 
748   return true;
749 }
750 
751 /* We've just seen template <>.  */
752 
753 bool
begin_specialization(void)754 begin_specialization (void)
755 {
756   begin_scope (sk_template_spec, NULL);
757   note_template_header (1);
758   return check_specialization_scope ();
759 }
760 
761 /* Called at then end of processing a declaration preceded by
762    template<>.  */
763 
764 void
end_specialization(void)765 end_specialization (void)
766 {
767   finish_scope ();
768   reset_specialization ();
769 }
770 
771 /* Any template <>'s that we have seen thus far are not referring to a
772    function specialization.  */
773 
774 void
reset_specialization(void)775 reset_specialization (void)
776 {
777   processing_specialization = 0;
778   template_header_count = 0;
779 }
780 
781 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
782    it was of the form template <>.  */
783 
784 static void
note_template_header(int specialization)785 note_template_header (int specialization)
786 {
787   processing_specialization = specialization;
788   template_header_count++;
789 }
790 
791 /* We're beginning an explicit instantiation.  */
792 
793 void
begin_explicit_instantiation(void)794 begin_explicit_instantiation (void)
795 {
796   gcc_assert (!processing_explicit_instantiation);
797   processing_explicit_instantiation = true;
798 }
799 
800 
801 void
end_explicit_instantiation(void)802 end_explicit_instantiation (void)
803 {
804   gcc_assert (processing_explicit_instantiation);
805   processing_explicit_instantiation = false;
806 }
807 
808 /* An explicit specialization or partial specialization of TMPL is being
809    declared.  Check that the namespace in which the specialization is
810    occurring is permissible.  Returns false iff it is invalid to
811    specialize TMPL in the current namespace.  */
812 
813 static bool
check_specialization_namespace(tree tmpl)814 check_specialization_namespace (tree tmpl)
815 {
816   tree tpl_ns = decl_namespace_context (tmpl);
817 
818   /* [tmpl.expl.spec]
819 
820      An explicit specialization shall be declared in a namespace enclosing the
821      specialized template. An explicit specialization whose declarator-id is
822      not qualified shall be declared in the nearest enclosing namespace of the
823      template, or, if the namespace is inline (7.3.1), any namespace from its
824      enclosing namespace set.  */
825   if (current_scope() != DECL_CONTEXT (tmpl)
826       && !at_namespace_scope_p ())
827     {
828       error ("specialization of %qD must appear at namespace scope", tmpl);
829       return false;
830     }
831 
832   if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
833     /* Same or enclosing namespace.  */
834     return true;
835   else
836     {
837       auto_diagnostic_group d;
838       if (permerror (input_location,
839 		     "specialization of %qD in different namespace", tmpl))
840 	inform (DECL_SOURCE_LOCATION (tmpl),
841 		"  from definition of %q#D", tmpl);
842       return false;
843     }
844 }
845 
846 /* SPEC is an explicit instantiation.  Check that it is valid to
847    perform this explicit instantiation in the current namespace.  */
848 
849 static void
check_explicit_instantiation_namespace(tree spec)850 check_explicit_instantiation_namespace (tree spec)
851 {
852   tree ns;
853 
854   /* DR 275: An explicit instantiation shall appear in an enclosing
855      namespace of its template.  */
856   ns = decl_namespace_context (spec);
857   if (!is_nested_namespace (current_namespace, ns))
858     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
859 	       "(which does not enclose namespace %qD)",
860 	       spec, current_namespace, ns);
861 }
862 
863 /* Returns the type of a template specialization only if that
864    specialization needs to be defined. Otherwise (e.g., if the type has
865    already been defined), the function returns NULL_TREE.  */
866 
867 static tree
maybe_new_partial_specialization(tree type)868 maybe_new_partial_specialization (tree type)
869 {
870   /* An implicit instantiation of an incomplete type implies
871      the definition of a new class template.
872 
873 	template<typename T>
874 	  struct S;
875 
876 	template<typename T>
877 	  struct S<T*>;
878 
879      Here, S<T*> is an implicit instantiation of S whose type
880      is incomplete.  */
881   if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
882     return type;
883 
884   /* It can also be the case that TYPE is a completed specialization.
885      Continuing the previous example, suppose we also declare:
886 
887 	template<typename T>
888 	  requires Integral<T>
889 	    struct S<T*>;
890 
891      Here, S<T*> refers to the specialization S<T*> defined
892      above. However, we need to differentiate definitions because
893      we intend to define a new partial specialization. In this case,
894      we rely on the fact that the constraints are different for
895      this declaration than that above.
896 
897      Note that we also get here for injected class names and
898      late-parsed template definitions. We must ensure that we
899      do not create new type declarations for those cases.  */
900   if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
901     {
902       tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
903       tree args = CLASSTYPE_TI_ARGS (type);
904 
905       /* If there are no template parameters, this cannot be a new
906 	 partial template specialization?  */
907       if (!current_template_parms)
908         return NULL_TREE;
909 
910       /* The injected-class-name is not a new partial specialization.  */
911       if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
912 	return NULL_TREE;
913 
914       /* If the constraints are not the same as those of the primary
915 	 then, we can probably create a new specialization.  */
916       tree type_constr = current_template_constraints ();
917 
918       if (type == TREE_TYPE (tmpl))
919 	{
920 	  tree main_constr = get_constraints (tmpl);
921 	  if (equivalent_constraints (type_constr, main_constr))
922 	    return NULL_TREE;
923 	}
924 
925       /* Also, if there's a pre-existing specialization with matching
926 	 constraints, then this also isn't new.  */
927       tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
928       while (specs)
929         {
930           tree spec_tmpl = TREE_VALUE (specs);
931           tree spec_args = TREE_PURPOSE (specs);
932           tree spec_constr = get_constraints (spec_tmpl);
933           if (comp_template_args (args, spec_args)
934 	      && equivalent_constraints (type_constr, spec_constr))
935             return NULL_TREE;
936           specs = TREE_CHAIN (specs);
937         }
938 
939       /* Create a new type node (and corresponding type decl)
940 	 for the newly declared specialization.  */
941       tree t = make_class_type (TREE_CODE (type));
942       CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
943       SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
944 
945       /* We only need a separate type node for storing the definition of this
946 	 partial specialization; uses of S<T*> are unconstrained, so all are
947 	 equivalent.  So keep TYPE_CANONICAL the same.  */
948       TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
949 
950       /* Build the corresponding type decl.  */
951       tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
952       DECL_CONTEXT (d) = TYPE_CONTEXT (t);
953       DECL_SOURCE_LOCATION (d) = input_location;
954       TREE_PRIVATE (d) = (current_access_specifier == access_private_node);
955       TREE_PROTECTED (d) = (current_access_specifier == access_protected_node);
956 
957       return t;
958     }
959 
960   return NULL_TREE;
961 }
962 
963 /* The TYPE is being declared.  If it is a template type, that means it
964    is a partial specialization.  Do appropriate error-checking.  */
965 
966 tree
maybe_process_partial_specialization(tree type)967 maybe_process_partial_specialization (tree type)
968 {
969   tree context;
970 
971   if (type == error_mark_node)
972     return error_mark_node;
973 
974   /* A lambda that appears in specialization context is not itself a
975      specialization.  */
976   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
977     return type;
978 
979   /* An injected-class-name is not a specialization.  */
980   if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
981     return type;
982 
983   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
984     {
985       error ("name of class shadows template template parameter %qD",
986 	     TYPE_NAME (type));
987       return error_mark_node;
988     }
989 
990   context = TYPE_CONTEXT (type);
991 
992   if (TYPE_ALIAS_P (type))
993     {
994       tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
995 
996       if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
997 	error ("specialization of alias template %qD",
998 	       TI_TEMPLATE (tinfo));
999       else
1000 	error ("explicit specialization of non-template %qT", type);
1001       return error_mark_node;
1002     }
1003   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
1004     {
1005       /* This is for ordinary explicit specialization and partial
1006 	 specialization of a template class such as:
1007 
1008 	   template <> class C<int>;
1009 
1010 	 or:
1011 
1012 	   template <class T> class C<T*>;
1013 
1014 	 Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
1015 
1016       if (tree t = maybe_new_partial_specialization (type))
1017 	{
1018 	  if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (t))
1019 	      && !at_namespace_scope_p ())
1020 	    return error_mark_node;
1021 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (t);
1022 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (t)) = input_location;
1023 	  if (processing_template_decl)
1024 	    {
1025 	      tree decl = push_template_decl (TYPE_MAIN_DECL (t));
1026 	      if (decl == error_mark_node)
1027 		return error_mark_node;
1028 	      return TREE_TYPE (decl);
1029 	    }
1030 	}
1031       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
1032 	error ("specialization of %qT after instantiation", type);
1033       else if (errorcount && !processing_specialization
1034 	        && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
1035 	       && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
1036 	/* Trying to define a specialization either without a template<> header
1037 	   or in an inappropriate place.  We've already given an error, so just
1038 	   bail now so we don't actually define the specialization.  */
1039 	return error_mark_node;
1040     }
1041   else if (CLASS_TYPE_P (type)
1042 	   && !CLASSTYPE_USE_TEMPLATE (type)
1043 	   && CLASSTYPE_TEMPLATE_INFO (type)
1044 	   && context && CLASS_TYPE_P (context)
1045 	   && CLASSTYPE_TEMPLATE_INFO (context))
1046     {
1047       /* This is for an explicit specialization of member class
1048 	 template according to [temp.expl.spec/18]:
1049 
1050 	   template <> template <class U> class C<int>::D;
1051 
1052 	 The context `C<int>' must be an implicit instantiation.
1053 	 Otherwise this is just a member class template declared
1054 	 earlier like:
1055 
1056 	   template <> class C<int> { template <class U> class D; };
1057 	   template <> template <class U> class C<int>::D;
1058 
1059 	 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1060 	 while in the second case, `C<int>::D' is a primary template
1061 	 and `C<T>::D' may not exist.  */
1062 
1063       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1064 	  && !COMPLETE_TYPE_P (type))
1065 	{
1066 	  tree t;
1067 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1068 
1069 	  if (current_namespace
1070 	      != decl_namespace_context (tmpl))
1071 	    {
1072 	      if (permerror (input_location,
1073 			     "specialization of %qD in different namespace",
1074 			     type))
1075 		inform (DECL_SOURCE_LOCATION (tmpl),
1076 			"from definition of %q#D", tmpl);
1077 	    }
1078 
1079 	  /* Check for invalid specialization after instantiation:
1080 
1081 	       template <> template <> class C<int>::D<int>;
1082 	       template <> template <class U> class C<int>::D;  */
1083 
1084 	  for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1085 	       t; t = TREE_CHAIN (t))
1086 	    {
1087 	      tree inst = TREE_VALUE (t);
1088 	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1089 		  || !COMPLETE_OR_OPEN_TYPE_P (inst))
1090 		{
1091 		  /* We already have a full specialization of this partial
1092 		     instantiation, or a full specialization has been
1093 		     looked up but not instantiated.  Reassign it to the
1094 		     new member specialization template.  */
1095 		  spec_entry elt;
1096 		  spec_entry *entry;
1097 
1098 		  elt.tmpl = most_general_template (tmpl);
1099 		  elt.args = CLASSTYPE_TI_ARGS (inst);
1100 		  elt.spec = inst;
1101 
1102 		  type_specializations->remove_elt (&elt);
1103 
1104 		  elt.tmpl = tmpl;
1105 		  CLASSTYPE_TI_ARGS (inst)
1106 		    = elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1107 
1108 		  spec_entry **slot
1109 		    = type_specializations->find_slot (&elt, INSERT);
1110 		  entry = ggc_alloc<spec_entry> ();
1111 		  *entry = elt;
1112 		  *slot = entry;
1113 		}
1114 	      else
1115 		/* But if we've had an implicit instantiation, that's a
1116 		   problem ([temp.expl.spec]/6).  */
1117 		error ("specialization %qT after instantiation %qT",
1118 		       type, inst);
1119 	    }
1120 
1121 	  /* Mark TYPE as a specialization.  And as a result, we only
1122 	     have one level of template argument for the innermost
1123 	     class template.  */
1124 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1125 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1126 	  CLASSTYPE_TI_ARGS (type)
1127 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1128 	}
1129     }
1130   else if (processing_specialization)
1131     {
1132        /* Someday C++0x may allow for enum template specialization.  */
1133       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1134 	  && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1135 	pedwarn (input_location, OPT_Wpedantic, "template specialization "
1136 		 "of %qD not allowed by ISO C++", type);
1137       else
1138 	{
1139 	  error ("explicit specialization of non-template %qT", type);
1140 	  return error_mark_node;
1141 	}
1142     }
1143 
1144   return type;
1145 }
1146 
1147 /* Returns nonzero if we can optimize the retrieval of specializations
1148    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
1149    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
1150 
1151 static inline bool
optimize_specialization_lookup_p(tree tmpl)1152 optimize_specialization_lookup_p (tree tmpl)
1153 {
1154   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1155 	  && DECL_CLASS_SCOPE_P (tmpl)
1156 	  /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1157 	     parameter.  */
1158 	  && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1159 	  /* The optimized lookup depends on the fact that the
1160 	     template arguments for the member function template apply
1161 	     purely to the containing class, which is not true if the
1162 	     containing class is an explicit or partial
1163 	     specialization.  */
1164 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1165 	  && !DECL_MEMBER_TEMPLATE_P (tmpl)
1166 	  && !DECL_CONV_FN_P (tmpl)
1167 	  /* It is possible to have a template that is not a member
1168 	     template and is not a member of a template class:
1169 
1170 	     template <typename T>
1171 	     struct S { friend A::f(); };
1172 
1173 	     Here, the friend function is a template, but the context does
1174 	     not have template information.  The optimized lookup relies
1175 	     on having ARGS be the template arguments for both the class
1176 	     and the function template.  */
1177 	  && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1178 }
1179 
1180 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1181    gone through coerce_template_parms by now.  */
1182 
1183 static void
verify_unstripped_args_1(tree inner)1184 verify_unstripped_args_1 (tree inner)
1185 {
1186   for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1187     {
1188       tree arg = TREE_VEC_ELT (inner, i);
1189       if (TREE_CODE (arg) == TEMPLATE_DECL)
1190 	/* OK */;
1191       else if (TYPE_P (arg))
1192 	gcc_assert (strip_typedefs (arg, NULL) == arg);
1193       else if (ARGUMENT_PACK_P (arg))
1194 	verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1195       else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1196 	/* Allow typedefs on the type of a non-type argument, since a
1197 	   parameter can have them.  */;
1198       else
1199 	gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1200     }
1201 }
1202 
1203 static void
verify_unstripped_args(tree args)1204 verify_unstripped_args (tree args)
1205 {
1206   ++processing_template_decl;
1207   if (!any_dependent_template_arguments_p (args))
1208     verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1209   --processing_template_decl;
1210 }
1211 
1212 /* Retrieve the specialization (in the sense of [temp.spec] - a
1213    specialization is either an instantiation or an explicit
1214    specialization) of TMPL for the given template ARGS.  If there is
1215    no such specialization, return NULL_TREE.  The ARGS are a vector of
1216    arguments, or a vector of vectors of arguments, in the case of
1217    templates with more than one level of parameters.
1218 
1219    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1220    then we search for a partial specialization matching ARGS.  This
1221    parameter is ignored if TMPL is not a class template.
1222 
1223    We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1224    result is a NONTYPE_ARGUMENT_PACK.  */
1225 
1226 static tree
retrieve_specialization(tree tmpl,tree args,hashval_t hash)1227 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1228 {
1229   if (tmpl == NULL_TREE)
1230     return NULL_TREE;
1231 
1232   if (args == error_mark_node)
1233     return NULL_TREE;
1234 
1235   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1236 	      || TREE_CODE (tmpl) == FIELD_DECL);
1237 
1238   /* There should be as many levels of arguments as there are
1239      levels of parameters.  */
1240   gcc_assert (TMPL_ARGS_DEPTH (args)
1241 	      == (TREE_CODE (tmpl) == TEMPLATE_DECL
1242 		  ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1243 		  : template_class_depth (DECL_CONTEXT (tmpl))));
1244 
1245   if (flag_checking)
1246     verify_unstripped_args (args);
1247 
1248   /* Lambda functions in templates aren't instantiated normally, but through
1249      tsubst_lambda_expr.  */
1250   if (lambda_fn_in_template_p (tmpl))
1251     return NULL_TREE;
1252 
1253   if (optimize_specialization_lookup_p (tmpl))
1254     {
1255       /* The template arguments actually apply to the containing
1256 	 class.  Find the class specialization with those
1257 	 arguments.  */
1258       tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1259       tree class_specialization
1260 	= retrieve_specialization (class_template, args, 0);
1261       if (!class_specialization)
1262 	return NULL_TREE;
1263 
1264       /* Find the instance of TMPL.  */
1265       tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1266       for (ovl_iterator iter (fns); iter; ++iter)
1267 	{
1268 	  tree fn = *iter;
1269 	  if (tree ti = get_template_info (fn))
1270 	    if (TI_TEMPLATE (ti) == tmpl
1271 		/* using-declarations can bring in a different
1272 		   instantiation of tmpl as a member of a different
1273 		   instantiation of tmpl's class.  We don't want those
1274 		   here.  */
1275 		&& DECL_CONTEXT (fn) == class_specialization)
1276 	      return fn;
1277 	}
1278       return NULL_TREE;
1279     }
1280   else
1281     {
1282       spec_entry *found;
1283       spec_entry elt;
1284       hash_table<spec_hasher> *specializations;
1285 
1286       elt.tmpl = tmpl;
1287       elt.args = args;
1288       elt.spec = NULL_TREE;
1289 
1290       if (DECL_CLASS_TEMPLATE_P (tmpl))
1291 	specializations = type_specializations;
1292       else
1293 	specializations = decl_specializations;
1294 
1295       if (hash == 0)
1296 	hash = spec_hasher::hash (&elt);
1297       found = specializations->find_with_hash (&elt, hash);
1298       if (found)
1299 	return found->spec;
1300     }
1301 
1302   return NULL_TREE;
1303 }
1304 
1305 /* Like retrieve_specialization, but for local declarations.  */
1306 
1307 tree
retrieve_local_specialization(tree tmpl)1308 retrieve_local_specialization (tree tmpl)
1309 {
1310   if (local_specializations == NULL)
1311     return NULL_TREE;
1312 
1313   tree *slot = local_specializations->get (tmpl);
1314   return slot ? *slot : NULL_TREE;
1315 }
1316 
1317 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1318 
1319 int
is_specialization_of(tree decl,tree tmpl)1320 is_specialization_of (tree decl, tree tmpl)
1321 {
1322   tree t;
1323 
1324   if (TREE_CODE (decl) == FUNCTION_DECL)
1325     {
1326       for (t = decl;
1327 	   t != NULL_TREE;
1328 	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1329 	if (t == tmpl)
1330 	  return 1;
1331     }
1332   else
1333     {
1334       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1335 
1336       for (t = TREE_TYPE (decl);
1337 	   t != NULL_TREE;
1338 	   t = CLASSTYPE_USE_TEMPLATE (t)
1339 	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1340 	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1341 	  return 1;
1342     }
1343 
1344   return 0;
1345 }
1346 
1347 /* Returns nonzero iff DECL is a specialization of friend declaration
1348    FRIEND_DECL according to [temp.friend].  */
1349 
1350 bool
is_specialization_of_friend(tree decl,tree friend_decl)1351 is_specialization_of_friend (tree decl, tree friend_decl)
1352 {
1353   bool need_template = true;
1354   int template_depth;
1355 
1356   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1357 	      || TREE_CODE (decl) == TYPE_DECL);
1358 
1359   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1360      of a template class, we want to check if DECL is a specialization
1361      if this.  */
1362   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1363       && DECL_TEMPLATE_INFO (friend_decl)
1364       && !DECL_USE_TEMPLATE (friend_decl))
1365     {
1366       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1367       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1368       need_template = false;
1369     }
1370   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1371 	   && !PRIMARY_TEMPLATE_P (friend_decl))
1372     need_template = false;
1373 
1374   /* There is nothing to do if this is not a template friend.  */
1375   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1376     return false;
1377 
1378   if (is_specialization_of (decl, friend_decl))
1379     return true;
1380 
1381   /* [temp.friend/6]
1382      A member of a class template may be declared to be a friend of a
1383      non-template class.  In this case, the corresponding member of
1384      every specialization of the class template is a friend of the
1385      class granting friendship.
1386 
1387      For example, given a template friend declaration
1388 
1389        template <class T> friend void A<T>::f();
1390 
1391      the member function below is considered a friend
1392 
1393        template <> struct A<int> {
1394 	 void f();
1395        };
1396 
1397      For this type of template friend, TEMPLATE_DEPTH below will be
1398      nonzero.  To determine if DECL is a friend of FRIEND, we first
1399      check if the enclosing class is a specialization of another.  */
1400 
1401   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1402   if (template_depth
1403       && DECL_CLASS_SCOPE_P (decl)
1404       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1405 			       CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1406     {
1407       /* Next, we check the members themselves.  In order to handle
1408 	 a few tricky cases, such as when FRIEND_DECL's are
1409 
1410 	   template <class T> friend void A<T>::g(T t);
1411 	   template <class T> template <T t> friend void A<T>::h();
1412 
1413 	 and DECL's are
1414 
1415 	   void A<int>::g(int);
1416 	   template <int> void A<int>::h();
1417 
1418 	 we need to figure out ARGS, the template arguments from
1419 	 the context of DECL.  This is required for template substitution
1420 	 of `T' in the function parameter of `g' and template parameter
1421 	 of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1422 
1423       tree context = DECL_CONTEXT (decl);
1424       tree args = NULL_TREE;
1425       int current_depth = 0;
1426 
1427       while (current_depth < template_depth)
1428 	{
1429 	  if (CLASSTYPE_TEMPLATE_INFO (context))
1430 	    {
1431 	      if (current_depth == 0)
1432 		args = TYPE_TI_ARGS (context);
1433 	      else
1434 		args = add_to_template_args (TYPE_TI_ARGS (context), args);
1435 	      current_depth++;
1436 	    }
1437 	  context = TYPE_CONTEXT (context);
1438 	}
1439 
1440       if (TREE_CODE (decl) == FUNCTION_DECL)
1441 	{
1442 	  bool is_template;
1443 	  tree friend_type;
1444 	  tree decl_type;
1445 	  tree friend_args_type;
1446 	  tree decl_args_type;
1447 
1448 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1449 	     non-templates.  */
1450 	  is_template = DECL_TEMPLATE_INFO (decl)
1451 			&& PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1452 	  if (need_template ^ is_template)
1453 	    return false;
1454 	  else if (is_template)
1455 	    {
1456 	      /* If both are templates, check template parameter list.  */
1457 	      tree friend_parms
1458 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1459 					 args, tf_none);
1460 	      if (!comp_template_parms
1461 		     (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1462 		      friend_parms))
1463 		return false;
1464 
1465 	      decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1466 	    }
1467 	  else
1468 	    decl_type = TREE_TYPE (decl);
1469 
1470 	  friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1471 					      tf_none, NULL_TREE);
1472 	  if (friend_type == error_mark_node)
1473 	    return false;
1474 
1475 	  /* Check if return types match.  */
1476 	  if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1477 	    return false;
1478 
1479 	  /* Check if function parameter types match, ignoring the
1480 	     `this' parameter.  */
1481 	  friend_args_type = TYPE_ARG_TYPES (friend_type);
1482 	  decl_args_type = TYPE_ARG_TYPES (decl_type);
1483 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1484 	    friend_args_type = TREE_CHAIN (friend_args_type);
1485 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1486 	    decl_args_type = TREE_CHAIN (decl_args_type);
1487 
1488 	  return compparms (decl_args_type, friend_args_type);
1489 	}
1490       else
1491 	{
1492 	  /* DECL is a TYPE_DECL */
1493 	  bool is_template;
1494 	  tree decl_type = TREE_TYPE (decl);
1495 
1496 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1497 	     non-templates.  */
1498 	  is_template
1499 	    = CLASSTYPE_TEMPLATE_INFO (decl_type)
1500 	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1501 
1502 	  if (need_template ^ is_template)
1503 	    return false;
1504 	  else if (is_template)
1505 	    {
1506 	      tree friend_parms;
1507 	      /* If both are templates, check the name of the two
1508 		 TEMPLATE_DECL's first because is_friend didn't.  */
1509 	      if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1510 		  != DECL_NAME (friend_decl))
1511 		return false;
1512 
1513 	      /* Now check template parameter list.  */
1514 	      friend_parms
1515 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1516 					 args, tf_none);
1517 	      return comp_template_parms
1518 		(DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1519 		 friend_parms);
1520 	    }
1521 	  else
1522 	    return (DECL_NAME (decl)
1523 		    == DECL_NAME (friend_decl));
1524 	}
1525     }
1526   return false;
1527 }
1528 
1529 /* Register the specialization SPEC as a specialization of TMPL with
1530    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1531    is actually just a friend declaration.  ATTRLIST is the list of
1532    attributes that the specialization is declared with or NULL when
1533    it isn't.  Returns SPEC, or an equivalent prior declaration, if
1534    available.
1535 
1536    We also store instantiations of field packs in the hash table, even
1537    though they are not themselves templates, to make lookup easier.  */
1538 
1539 static tree
register_specialization(tree spec,tree tmpl,tree args,bool is_friend,hashval_t hash)1540 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1541 			 hashval_t hash)
1542 {
1543   tree fn;
1544   spec_entry **slot = NULL;
1545   spec_entry elt;
1546 
1547   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1548 	      || (TREE_CODE (tmpl) == FIELD_DECL
1549 		  && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1550 
1551   if (TREE_CODE (spec) == FUNCTION_DECL
1552       && uses_template_parms (DECL_TI_ARGS (spec)))
1553     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1554        register it; we want the corresponding TEMPLATE_DECL instead.
1555        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1556        the more obvious `uses_template_parms (spec)' to avoid problems
1557        with default function arguments.  In particular, given
1558        something like this:
1559 
1560 	  template <class T> void f(T t1, T t = T())
1561 
1562        the default argument expression is not substituted for in an
1563        instantiation unless and until it is actually needed.  */
1564     return spec;
1565 
1566   if (optimize_specialization_lookup_p (tmpl))
1567     /* We don't put these specializations in the hash table, but we might
1568        want to give an error about a mismatch.  */
1569     fn = retrieve_specialization (tmpl, args, 0);
1570   else
1571     {
1572       elt.tmpl = tmpl;
1573       elt.args = args;
1574       elt.spec = spec;
1575 
1576       if (hash == 0)
1577 	hash = spec_hasher::hash (&elt);
1578 
1579       slot =
1580 	decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1581       if (*slot)
1582 	fn = ((spec_entry *) *slot)->spec;
1583       else
1584 	fn = NULL_TREE;
1585     }
1586 
1587   /* We can sometimes try to re-register a specialization that we've
1588      already got.  In particular, regenerate_decl_from_template calls
1589      duplicate_decls which will update the specialization list.  But,
1590      we'll still get called again here anyhow.  It's more convenient
1591      to simply allow this than to try to prevent it.  */
1592   if (fn == spec)
1593     return spec;
1594   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1595     {
1596       if (DECL_TEMPLATE_INSTANTIATION (fn))
1597 	{
1598 	  if (DECL_ODR_USED (fn)
1599 	      || DECL_EXPLICIT_INSTANTIATION (fn))
1600 	    {
1601 	      error ("specialization of %qD after instantiation",
1602 		     fn);
1603 	      return error_mark_node;
1604 	    }
1605 	  else
1606 	    {
1607 	      tree clone;
1608 	      /* This situation should occur only if the first
1609 		 specialization is an implicit instantiation, the
1610 		 second is an explicit specialization, and the
1611 		 implicit instantiation has not yet been used.  That
1612 		 situation can occur if we have implicitly
1613 		 instantiated a member function and then specialized
1614 		 it later.
1615 
1616 		 We can also wind up here if a friend declaration that
1617 		 looked like an instantiation turns out to be a
1618 		 specialization:
1619 
1620 		   template <class T> void foo(T);
1621 		   class S { friend void foo<>(int) };
1622 		   template <> void foo(int);
1623 
1624 		 We transform the existing DECL in place so that any
1625 		 pointers to it become pointers to the updated
1626 		 declaration.
1627 
1628 		 If there was a definition for the template, but not
1629 		 for the specialization, we want this to look as if
1630 		 there were no definition, and vice versa.  */
1631 	      DECL_INITIAL (fn) = NULL_TREE;
1632 	      duplicate_decls (spec, fn, is_friend);
1633 	      /* The call to duplicate_decls will have applied
1634 		 [temp.expl.spec]:
1635 
1636 		   An explicit specialization of a function template
1637 		   is inline only if it is explicitly declared to be,
1638 		   and independently of whether its function template
1639 		   is.
1640 
1641 		to the primary function; now copy the inline bits to
1642 		the various clones.  */
1643 	      FOR_EACH_CLONE (clone, fn)
1644 		{
1645 		  DECL_DECLARED_INLINE_P (clone)
1646 		    = DECL_DECLARED_INLINE_P (fn);
1647 		  DECL_SOURCE_LOCATION (clone)
1648 		    = DECL_SOURCE_LOCATION (fn);
1649 		  DECL_DELETED_FN (clone)
1650 		    = DECL_DELETED_FN (fn);
1651 		}
1652 	      check_specialization_namespace (tmpl);
1653 
1654 	      return fn;
1655 	    }
1656 	}
1657       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1658 	{
1659 	  tree dd = duplicate_decls (spec, fn, is_friend);
1660 	  if (dd == error_mark_node)
1661 	    /* We've already complained in duplicate_decls.  */
1662 	    return error_mark_node;
1663 
1664 	  if (dd == NULL_TREE && DECL_INITIAL (spec))
1665 	    /* Dup decl failed, but this is a new definition. Set the
1666 	       line number so any errors match this new
1667 	       definition.  */
1668 	    DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1669 
1670 	  return fn;
1671 	}
1672     }
1673   else if (fn)
1674     return duplicate_decls (spec, fn, is_friend);
1675 
1676   /* A specialization must be declared in the same namespace as the
1677      template it is specializing.  */
1678   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1679       && !check_specialization_namespace (tmpl))
1680     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1681 
1682   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1683     {
1684       spec_entry *entry = ggc_alloc<spec_entry> ();
1685       gcc_assert (tmpl && args && spec);
1686       *entry = elt;
1687       *slot = entry;
1688       if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1689 	   && PRIMARY_TEMPLATE_P (tmpl)
1690 	   && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1691 	  || variable_template_p (tmpl))
1692 	/* If TMPL is a forward declaration of a template function, keep a list
1693 	   of all specializations in case we need to reassign them to a friend
1694 	   template later in tsubst_friend_function.
1695 
1696 	   Also keep a list of all variable template instantiations so that
1697 	   process_partial_specialization can check whether a later partial
1698 	   specialization would have used it.  */
1699 	DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1700 	  = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1701     }
1702 
1703   return spec;
1704 }
1705 
1706 /* Returns true iff two spec_entry nodes are equivalent.  */
1707 
1708 int comparing_specializations;
1709 
1710 bool
equal(spec_entry * e1,spec_entry * e2)1711 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1712 {
1713   int equal;
1714 
1715   ++comparing_specializations;
1716   equal = (e1->tmpl == e2->tmpl
1717 	   && comp_template_args (e1->args, e2->args));
1718   if (equal && flag_concepts
1719       /* tmpl could be a FIELD_DECL for a capture pack.  */
1720       && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1721       && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1722       && uses_template_parms (e1->args))
1723     {
1724       /* Partial specializations of a variable template can be distinguished by
1725 	 constraints.  */
1726       tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1727       tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1728       equal = equivalent_constraints (c1, c2);
1729     }
1730   --comparing_specializations;
1731 
1732   return equal;
1733 }
1734 
1735 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1736 
1737 static hashval_t
hash_tmpl_and_args(tree tmpl,tree args)1738 hash_tmpl_and_args (tree tmpl, tree args)
1739 {
1740   hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1741   return iterative_hash_template_arg (args, val);
1742 }
1743 
1744 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1745    ignoring SPEC.  */
1746 
1747 hashval_t
hash(spec_entry * e)1748 spec_hasher::hash (spec_entry *e)
1749 {
1750   return hash_tmpl_and_args (e->tmpl, e->args);
1751 }
1752 
1753 /* Recursively calculate a hash value for a template argument ARG, for use
1754    in the hash tables of template specializations.   We must be
1755    careful to (at least) skip the same entities template_args_equal
1756    does.  */
1757 
1758 hashval_t
iterative_hash_template_arg(tree arg,hashval_t val)1759 iterative_hash_template_arg (tree arg, hashval_t val)
1760 {
1761   if (arg == NULL_TREE)
1762     return iterative_hash_object (arg, val);
1763 
1764   if (!TYPE_P (arg))
1765     /* Strip nop-like things, but not the same as STRIP_NOPS.  */
1766     while (CONVERT_EXPR_P (arg)
1767 	   || TREE_CODE (arg) == NON_LVALUE_EXPR
1768 	   || class_nttp_const_wrapper_p (arg))
1769       arg = TREE_OPERAND (arg, 0);
1770 
1771   enum tree_code code = TREE_CODE (arg);
1772 
1773   val = iterative_hash_object (code, val);
1774 
1775   switch (code)
1776     {
1777     case ARGUMENT_PACK_SELECT:
1778       gcc_unreachable ();
1779 
1780     case ERROR_MARK:
1781       return val;
1782 
1783     case IDENTIFIER_NODE:
1784       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1785 
1786     case TREE_VEC:
1787       for (int i = 0, len = TREE_VEC_LENGTH (arg); i < len; ++i)
1788 	val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1789       return val;
1790 
1791     case TYPE_PACK_EXPANSION:
1792     case EXPR_PACK_EXPANSION:
1793       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1794       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1795 
1796     case TYPE_ARGUMENT_PACK:
1797     case NONTYPE_ARGUMENT_PACK:
1798       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1799 
1800     case TREE_LIST:
1801       for (; arg; arg = TREE_CHAIN (arg))
1802 	val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1803       return val;
1804 
1805     case OVERLOAD:
1806       for (lkp_iterator iter (arg); iter; ++iter)
1807 	val = iterative_hash_template_arg (*iter, val);
1808       return val;
1809 
1810     case CONSTRUCTOR:
1811       {
1812 	tree field, value;
1813 	unsigned i;
1814 	iterative_hash_template_arg (TREE_TYPE (arg), val);
1815 	FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1816 	  {
1817 	    val = iterative_hash_template_arg (field, val);
1818 	    val = iterative_hash_template_arg (value, val);
1819 	  }
1820 	return val;
1821       }
1822 
1823     case PARM_DECL:
1824       if (!DECL_ARTIFICIAL (arg))
1825 	{
1826 	  val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1827 	  val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1828 	}
1829       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1830 
1831     case TARGET_EXPR:
1832       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1833 
1834     case PTRMEM_CST:
1835       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1836       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1837 
1838     case TEMPLATE_PARM_INDEX:
1839       val = iterative_hash_template_arg
1840 	(TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1841       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1842       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1843 
1844     case TRAIT_EXPR:
1845       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1846       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1847       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1848 
1849     case BASELINK:
1850       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1851 					 val);
1852       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1853 					  val);
1854 
1855     case MODOP_EXPR:
1856       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1857       code = TREE_CODE (TREE_OPERAND (arg, 1));
1858       val = iterative_hash_object (code, val);
1859       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1860 
1861     case LAMBDA_EXPR:
1862       /* [temp.over.link] Two lambda-expressions are never considered
1863 	 equivalent.
1864 
1865          So just hash the closure type.  */
1866       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1867 
1868     case CAST_EXPR:
1869     case IMPLICIT_CONV_EXPR:
1870     case STATIC_CAST_EXPR:
1871     case REINTERPRET_CAST_EXPR:
1872     case CONST_CAST_EXPR:
1873     case DYNAMIC_CAST_EXPR:
1874     case NEW_EXPR:
1875       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1876       /* Now hash operands as usual.  */
1877       break;
1878 
1879     case CALL_EXPR:
1880       {
1881 	tree fn = CALL_EXPR_FN (arg);
1882 	if (tree name = dependent_name (fn))
1883 	  {
1884 	    if (TREE_CODE (fn) == TEMPLATE_ID_EXPR)
1885 	      val = iterative_hash_template_arg (TREE_OPERAND (fn, 1), val);
1886 	    fn = name;
1887 	  }
1888 	val = iterative_hash_template_arg (fn, val);
1889 	call_expr_arg_iterator ai;
1890 	for (tree x = first_call_expr_arg (arg, &ai); x;
1891 	     x = next_call_expr_arg (&ai))
1892 	  val = iterative_hash_template_arg (x, val);
1893 	return val;
1894       }
1895 
1896     default:
1897       break;
1898     }
1899 
1900   char tclass = TREE_CODE_CLASS (code);
1901   switch (tclass)
1902     {
1903     case tcc_type:
1904       if (tree ats = alias_template_specialization_p (arg, nt_transparent))
1905 	{
1906 	  // We want an alias specialization that survived strip_typedefs
1907 	  // to hash differently from its TYPE_CANONICAL, to avoid hash
1908 	  // collisions that compare as different in template_args_equal.
1909 	  // These could be dependent specializations that strip_typedefs
1910 	  // left alone, or untouched specializations because
1911 	  // coerce_template_parms returns the unconverted template
1912 	  // arguments if it sees incomplete argument packs.
1913 	  tree ti = TYPE_ALIAS_TEMPLATE_INFO (ats);
1914 	  return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1915 	}
1916 
1917       switch (TREE_CODE (arg))
1918 	{
1919 	case TEMPLATE_TEMPLATE_PARM:
1920 	  {
1921 	    tree tpi = TEMPLATE_TYPE_PARM_INDEX (arg);
1922 
1923 	    /* Do not recurse with TPI directly, as that is unbounded
1924 	       recursion.  */
1925 	    val = iterative_hash_object (TEMPLATE_PARM_LEVEL (tpi), val);
1926 	    val = iterative_hash_object (TEMPLATE_PARM_IDX (tpi), val);
1927 	  }
1928 	  break;
1929 
1930 	case  DECLTYPE_TYPE:
1931 	  val = iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1932 	  break;
1933 
1934 	default:
1935 	  if (tree canonical = TYPE_CANONICAL (arg))
1936 	    val = iterative_hash_object (TYPE_HASH (canonical), val);
1937 	  break;
1938 	}
1939 
1940       return val;
1941 
1942     case tcc_declaration:
1943     case tcc_constant:
1944       return iterative_hash_expr (arg, val);
1945 
1946     default:
1947       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1948       for (int i = 0, n = cp_tree_operand_length (arg); i < n; ++i)
1949 	val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1950       return val;
1951     }
1952 
1953   gcc_unreachable ();
1954   return 0;
1955 }
1956 
1957 /* Unregister the specialization SPEC as a specialization of TMPL.
1958    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1959    if the SPEC was listed as a specialization of TMPL.
1960 
1961    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1962 
1963 bool
reregister_specialization(tree spec,tree tinfo,tree new_spec)1964 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1965 {
1966   spec_entry *entry;
1967   spec_entry elt;
1968 
1969   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1970   elt.args = TI_ARGS (tinfo);
1971   elt.spec = NULL_TREE;
1972 
1973   entry = decl_specializations->find (&elt);
1974   if (entry != NULL)
1975     {
1976       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1977       gcc_assert (new_spec != NULL_TREE);
1978       entry->spec = new_spec;
1979       return 1;
1980     }
1981 
1982   return 0;
1983 }
1984 
1985 /* Like register_specialization, but for local declarations.  We are
1986    registering SPEC, an instantiation of TMPL.  */
1987 
1988 void
register_local_specialization(tree spec,tree tmpl)1989 register_local_specialization (tree spec, tree tmpl)
1990 {
1991   gcc_assert (tmpl != spec);
1992   local_specializations->put (tmpl, spec);
1993 }
1994 
1995 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1996    specialized class.  */
1997 
1998 bool
explicit_class_specialization_p(tree type)1999 explicit_class_specialization_p (tree type)
2000 {
2001   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
2002     return false;
2003   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
2004 }
2005 
2006 /* Print the list of functions at FNS, going through all the overloads
2007    for each element of the list.  Alternatively, FNS cannot be a
2008    TREE_LIST, in which case it will be printed together with all the
2009    overloads.
2010 
2011    MORE and *STR should respectively be FALSE and NULL when the function
2012    is called from the outside.  They are used internally on recursive
2013    calls.  print_candidates manages the two parameters and leaves NULL
2014    in *STR when it ends.  */
2015 
2016 static void
2017 print_candidates_1 (tree fns, char **str, bool more = false)
2018 {
2019   if (TREE_CODE (fns) == TREE_LIST)
2020     for (; fns; fns = TREE_CHAIN (fns))
2021       print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
2022   else
2023     for (lkp_iterator iter (fns); iter;)
2024       {
2025 	tree cand = *iter;
2026 	++iter;
2027 
2028 	const char *pfx = *str;
2029 	if (!pfx)
2030 	  {
2031 	    if (more || iter)
2032 	      pfx = _("candidates are:");
2033 	    else
2034 	      pfx = _("candidate is:");
2035 	    *str = get_spaces (pfx);
2036 	  }
2037 	inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
2038       }
2039 }
2040 
2041 /* Print the list of candidate FNS in an error message.  FNS can also
2042    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
2043 
2044 void
print_candidates(tree fns)2045 print_candidates (tree fns)
2046 {
2047   char *str = NULL;
2048   print_candidates_1 (fns, &str);
2049   free (str);
2050 }
2051 
2052 /* Get a (possibly) constrained template declaration for the
2053    purpose of ordering candidates.  */
2054 static tree
get_template_for_ordering(tree list)2055 get_template_for_ordering (tree list)
2056 {
2057   gcc_assert (TREE_CODE (list) == TREE_LIST);
2058   tree f = TREE_VALUE (list);
2059   if (tree ti = DECL_TEMPLATE_INFO (f))
2060     return TI_TEMPLATE (ti);
2061   return f;
2062 }
2063 
2064 /* Among candidates having the same signature, return the
2065    most constrained or NULL_TREE if there is no best candidate.
2066    If the signatures of candidates vary (e.g., template
2067    specialization vs. member function), then there can be no
2068    most constrained.
2069 
2070    Note that we don't compare constraints on the functions
2071    themselves, but rather those of their templates. */
2072 static tree
most_constrained_function(tree candidates)2073 most_constrained_function (tree candidates)
2074 {
2075   // Try to find the best candidate in a first pass.
2076   tree champ = candidates;
2077   for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
2078     {
2079       int winner = more_constrained (get_template_for_ordering (champ),
2080                                      get_template_for_ordering (c));
2081       if (winner == -1)
2082         champ = c; // The candidate is more constrained
2083       else if (winner == 0)
2084         return NULL_TREE; // Neither is more constrained
2085     }
2086 
2087   // Verify that the champ is better than previous candidates.
2088   for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2089     if (!more_constrained (get_template_for_ordering (champ),
2090                            get_template_for_ordering (c)))
2091       return NULL_TREE;
2092   }
2093 
2094   return champ;
2095 }
2096 
2097 
2098 /* Returns the template (one of the functions given by TEMPLATE_ID)
2099    which can be specialized to match the indicated DECL with the
2100    explicit template args given in TEMPLATE_ID.  The DECL may be
2101    NULL_TREE if none is available.  In that case, the functions in
2102    TEMPLATE_ID are non-members.
2103 
2104    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2105    specialization of a member template.
2106 
2107    The TEMPLATE_COUNT is the number of references to qualifying
2108    template classes that appeared in the name of the function. See
2109    check_explicit_specialization for a more accurate description.
2110 
2111    TSK indicates what kind of template declaration (if any) is being
2112    declared.  TSK_TEMPLATE indicates that the declaration given by
2113    DECL, though a FUNCTION_DECL, has template parameters, and is
2114    therefore a template function.
2115 
2116    The template args (those explicitly specified and those deduced)
2117    are output in a newly created vector *TARGS_OUT.
2118 
2119    If it is impossible to determine the result, an error message is
2120    issued.  The error_mark_node is returned to indicate failure.  */
2121 
2122 static tree
determine_specialization(tree template_id,tree decl,tree * targs_out,int need_member_template,int template_count,tmpl_spec_kind tsk)2123 determine_specialization (tree template_id,
2124 			  tree decl,
2125 			  tree* targs_out,
2126 			  int need_member_template,
2127 			  int template_count,
2128 			  tmpl_spec_kind tsk)
2129 {
2130   tree fns;
2131   tree targs;
2132   tree explicit_targs;
2133   tree candidates = NULL_TREE;
2134 
2135   /* A TREE_LIST of templates of which DECL may be a specialization.
2136      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
2137      corresponding TREE_PURPOSE is the set of template arguments that,
2138      when used to instantiate the template, would produce a function
2139      with the signature of DECL.  */
2140   tree templates = NULL_TREE;
2141   int header_count;
2142   cp_binding_level *b;
2143 
2144   *targs_out = NULL_TREE;
2145 
2146   if (template_id == error_mark_node || decl == error_mark_node)
2147     return error_mark_node;
2148 
2149   /* We shouldn't be specializing a member template of an
2150      unspecialized class template; we already gave an error in
2151      check_specialization_scope, now avoid crashing.  */
2152   if (!VAR_P (decl)
2153       && template_count && DECL_CLASS_SCOPE_P (decl)
2154       && template_class_depth (DECL_CONTEXT (decl)) > 0)
2155     {
2156       gcc_assert (errorcount);
2157       return error_mark_node;
2158     }
2159 
2160   fns = TREE_OPERAND (template_id, 0);
2161   explicit_targs = TREE_OPERAND (template_id, 1);
2162 
2163   if (fns == error_mark_node)
2164     return error_mark_node;
2165 
2166   /* Check for baselinks.  */
2167   if (BASELINK_P (fns))
2168     fns = BASELINK_FUNCTIONS (fns);
2169 
2170   if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2171     {
2172       error_at (DECL_SOURCE_LOCATION (decl),
2173 		"%qD is not a function template", fns);
2174       return error_mark_node;
2175     }
2176   else if (VAR_P (decl) && !variable_template_p (fns))
2177     {
2178       error ("%qD is not a variable template", fns);
2179       return error_mark_node;
2180     }
2181 
2182   /* Count the number of template headers specified for this
2183      specialization.  */
2184   header_count = 0;
2185   for (b = current_binding_level;
2186        b->kind == sk_template_parms;
2187        b = b->level_chain)
2188     ++header_count;
2189 
2190   tree orig_fns = fns;
2191 
2192   if (variable_template_p (fns))
2193     {
2194       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2195       targs = coerce_template_parms (parms, explicit_targs, fns,
2196 				     tf_warning_or_error,
2197 				     /*req_all*/true, /*use_defarg*/true);
2198       if (targs != error_mark_node)
2199         templates = tree_cons (targs, fns, templates);
2200     }
2201   else for (lkp_iterator iter (fns); iter; ++iter)
2202     {
2203       tree fn = *iter;
2204 
2205       if (TREE_CODE (fn) == TEMPLATE_DECL)
2206 	{
2207 	  tree decl_arg_types;
2208 	  tree fn_arg_types;
2209 	  tree insttype;
2210 
2211 	  /* In case of explicit specialization, we need to check if
2212 	     the number of template headers appearing in the specialization
2213 	     is correct. This is usually done in check_explicit_specialization,
2214 	     but the check done there cannot be exhaustive when specializing
2215 	     member functions. Consider the following code:
2216 
2217 	     template <> void A<int>::f(int);
2218 	     template <> template <> void A<int>::f(int);
2219 
2220 	     Assuming that A<int> is not itself an explicit specialization
2221 	     already, the first line specializes "f" which is a non-template
2222 	     member function, whilst the second line specializes "f" which
2223 	     is a template member function. So both lines are syntactically
2224 	     correct, and check_explicit_specialization does not reject
2225 	     them.
2226 
2227 	     Here, we can do better, as we are matching the specialization
2228 	     against the declarations. We count the number of template
2229 	     headers, and we check if they match TEMPLATE_COUNT + 1
2230 	     (TEMPLATE_COUNT is the number of qualifying template classes,
2231 	     plus there must be another header for the member template
2232 	     itself).
2233 
2234 	     Notice that if header_count is zero, this is not a
2235 	     specialization but rather a template instantiation, so there
2236 	     is no check we can perform here.  */
2237 	  if (header_count && header_count != template_count + 1)
2238 	    continue;
2239 
2240 	  /* Check that the number of template arguments at the
2241 	     innermost level for DECL is the same as for FN.  */
2242 	  if (current_binding_level->kind == sk_template_parms
2243 	      && !current_binding_level->explicit_spec_p
2244 	      && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2245 		  != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2246 				      (current_template_parms))))
2247 	    continue;
2248 
2249 	  /* DECL might be a specialization of FN.  */
2250 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2251 	  fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2252 
2253 	  /* For a non-static member function, we need to make sure
2254 	     that the const qualification is the same.  Since
2255 	     get_bindings does not try to merge the "this" parameter,
2256 	     we must do the comparison explicitly.  */
2257 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2258 	    {
2259 	      if (!same_type_p (TREE_VALUE (fn_arg_types),
2260 				TREE_VALUE (decl_arg_types)))
2261 		continue;
2262 
2263 	      /* And the ref-qualification.  */
2264 	      if (type_memfn_rqual (TREE_TYPE (decl))
2265 		  != type_memfn_rqual (TREE_TYPE (fn)))
2266 		continue;
2267 	    }
2268 
2269 	  /* Skip the "this" parameter and, for constructors of
2270 	     classes with virtual bases, the VTT parameter.  A
2271 	     full specialization of a constructor will have a VTT
2272 	     parameter, but a template never will.  */
2273 	  decl_arg_types
2274 	    = skip_artificial_parms_for (decl, decl_arg_types);
2275 	  fn_arg_types
2276 	    = skip_artificial_parms_for (fn, fn_arg_types);
2277 
2278 	  /* Function templates cannot be specializations; there are
2279 	     no partial specializations of functions.  Therefore, if
2280 	     the type of DECL does not match FN, there is no
2281 	     match.
2282 
2283              Note that it should never be the case that we have both
2284              candidates added here, and for regular member functions
2285              below. */
2286 	  if (tsk == tsk_template)
2287 	    {
2288 	      if (compparms (fn_arg_types, decl_arg_types))
2289 		candidates = tree_cons (NULL_TREE, fn, candidates);
2290 	      continue;
2291 	    }
2292 
2293 	  /* See whether this function might be a specialization of this
2294 	     template.  Suppress access control because we might be trying
2295 	     to make this specialization a friend, and we have already done
2296 	     access control for the declaration of the specialization.  */
2297 	  push_deferring_access_checks (dk_no_check);
2298 	  targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2299 	  pop_deferring_access_checks ();
2300 
2301 	  if (!targs)
2302 	    /* We cannot deduce template arguments that when used to
2303 	       specialize TMPL will produce DECL.  */
2304 	    continue;
2305 
2306 	  if (uses_template_parms (targs))
2307 	    /* We deduced something involving 'auto', which isn't a valid
2308 	       template argument.  */
2309 	    continue;
2310 
2311           /* Remove, from the set of candidates, all those functions
2312              whose constraints are not satisfied. */
2313           if (flag_concepts && !constraints_satisfied_p (fn, targs))
2314             continue;
2315 
2316           // Then, try to form the new function type.
2317 	  insttype = tsubst (TREE_TYPE (fn), targs, tf_fndecl_type, NULL_TREE);
2318 	  if (insttype == error_mark_node)
2319 	    continue;
2320 	  fn_arg_types
2321 	    = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2322 	  if (!compparms (fn_arg_types, decl_arg_types))
2323 	    continue;
2324 
2325 	  /* Save this template, and the arguments deduced.  */
2326 	  templates = tree_cons (targs, fn, templates);
2327 	}
2328       else if (need_member_template)
2329 	/* FN is an ordinary member function, and we need a
2330 	   specialization of a member template.  */
2331 	;
2332       else if (TREE_CODE (fn) != FUNCTION_DECL)
2333 	/* We can get IDENTIFIER_NODEs here in certain erroneous
2334 	   cases.  */
2335 	;
2336       else if (!DECL_FUNCTION_MEMBER_P (fn))
2337 	/* This is just an ordinary non-member function.  Nothing can
2338 	   be a specialization of that.  */
2339 	;
2340       else if (DECL_ARTIFICIAL (fn))
2341 	/* Cannot specialize functions that are created implicitly.  */
2342 	;
2343       else
2344 	{
2345 	  tree decl_arg_types;
2346 
2347 	  /* This is an ordinary member function.  However, since
2348 	     we're here, we can assume its enclosing class is a
2349 	     template class.  For example,
2350 
2351 	       template <typename T> struct S { void f(); };
2352 	       template <> void S<int>::f() {}
2353 
2354 	     Here, S<int>::f is a non-template, but S<int> is a
2355 	     template class.  If FN has the same type as DECL, we
2356 	     might be in business.  */
2357 
2358 	  if (!DECL_TEMPLATE_INFO (fn))
2359 	    /* Its enclosing class is an explicit specialization
2360 	       of a template class.  This is not a candidate.  */
2361 	    continue;
2362 
2363 	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2364 			    TREE_TYPE (TREE_TYPE (fn))))
2365 	    /* The return types differ.  */
2366 	    continue;
2367 
2368 	  /* Adjust the type of DECL in case FN is a static member.  */
2369 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2370 	  if (DECL_STATIC_FUNCTION_P (fn)
2371 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2372 	    decl_arg_types = TREE_CHAIN (decl_arg_types);
2373 
2374 	  if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2375 			 decl_arg_types))
2376             continue;
2377 
2378 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2379 	      && (type_memfn_rqual (TREE_TYPE (decl))
2380 		  != type_memfn_rqual (TREE_TYPE (fn))))
2381 	    continue;
2382 
2383           // If the deduced arguments do not satisfy the constraints,
2384           // this is not a candidate.
2385           if (flag_concepts && !constraints_satisfied_p (fn))
2386             continue;
2387 
2388           // Add the candidate.
2389           candidates = tree_cons (NULL_TREE, fn, candidates);
2390 	}
2391     }
2392 
2393   if (templates && TREE_CHAIN (templates))
2394     {
2395       /* We have:
2396 
2397 	   [temp.expl.spec]
2398 
2399 	   It is possible for a specialization with a given function
2400 	   signature to be instantiated from more than one function
2401 	   template.  In such cases, explicit specification of the
2402 	   template arguments must be used to uniquely identify the
2403 	   function template specialization being specialized.
2404 
2405 	 Note that here, there's no suggestion that we're supposed to
2406 	 determine which of the candidate templates is most
2407 	 specialized.  However, we, also have:
2408 
2409 	   [temp.func.order]
2410 
2411 	   Partial ordering of overloaded function template
2412 	   declarations is used in the following contexts to select
2413 	   the function template to which a function template
2414 	   specialization refers:
2415 
2416 	   -- when an explicit specialization refers to a function
2417 	      template.
2418 
2419 	 So, we do use the partial ordering rules, at least for now.
2420 	 This extension can only serve to make invalid programs valid,
2421 	 so it's safe.  And, there is strong anecdotal evidence that
2422 	 the committee intended the partial ordering rules to apply;
2423 	 the EDG front end has that behavior, and John Spicer claims
2424 	 that the committee simply forgot to delete the wording in
2425 	 [temp.expl.spec].  */
2426       tree tmpl = most_specialized_instantiation (templates);
2427       if (tmpl != error_mark_node)
2428 	{
2429 	  templates = tmpl;
2430 	  TREE_CHAIN (templates) = NULL_TREE;
2431 	}
2432     }
2433 
2434   // Concepts allows multiple declarations of member functions
2435   // with the same signature. Like above, we need to rely on
2436   // on the partial ordering of those candidates to determine which
2437   // is the best.
2438   if (flag_concepts && candidates && TREE_CHAIN (candidates))
2439     {
2440       if (tree cand = most_constrained_function (candidates))
2441         {
2442           candidates = cand;
2443           TREE_CHAIN (cand) = NULL_TREE;
2444         }
2445     }
2446 
2447   if (templates == NULL_TREE && candidates == NULL_TREE)
2448     {
2449       error ("template-id %qD for %q+D does not match any template "
2450 	     "declaration", template_id, decl);
2451       if (header_count && header_count != template_count + 1)
2452 	inform (DECL_SOURCE_LOCATION (decl),
2453 		"saw %d %<template<>%>, need %d for "
2454 		"specializing a member function template",
2455 		header_count, template_count + 1);
2456       else
2457 	print_candidates (orig_fns);
2458       return error_mark_node;
2459     }
2460   else if ((templates && TREE_CHAIN (templates))
2461 	   || (candidates && TREE_CHAIN (candidates))
2462 	   || (templates && candidates))
2463     {
2464       error ("ambiguous template specialization %qD for %q+D",
2465 	     template_id, decl);
2466       candidates = chainon (candidates, templates);
2467       print_candidates (candidates);
2468       return error_mark_node;
2469     }
2470 
2471   /* We have one, and exactly one, match.  */
2472   if (candidates)
2473     {
2474       tree fn = TREE_VALUE (candidates);
2475       *targs_out = copy_node (DECL_TI_ARGS (fn));
2476 
2477       /* Propagate the candidate's constraints to the declaration.  */
2478       set_constraints (decl, get_constraints (fn));
2479 
2480       /* DECL is a re-declaration or partial instantiation of a template
2481 	 function.  */
2482       if (TREE_CODE (fn) == TEMPLATE_DECL)
2483 	return fn;
2484       /* It was a specialization of an ordinary member function in a
2485 	 template class.  */
2486       return DECL_TI_TEMPLATE (fn);
2487     }
2488 
2489   /* It was a specialization of a template.  */
2490   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2491   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2492     {
2493       *targs_out = copy_node (targs);
2494       SET_TMPL_ARGS_LEVEL (*targs_out,
2495 			   TMPL_ARGS_DEPTH (*targs_out),
2496 			   TREE_PURPOSE (templates));
2497     }
2498   else
2499     *targs_out = TREE_PURPOSE (templates);
2500   return TREE_VALUE (templates);
2501 }
2502 
2503 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2504    but with the default argument values filled in from those in the
2505    TMPL_TYPES.  */
2506 
2507 static tree
copy_default_args_to_explicit_spec_1(tree spec_types,tree tmpl_types)2508 copy_default_args_to_explicit_spec_1 (tree spec_types,
2509 				      tree tmpl_types)
2510 {
2511   tree new_spec_types;
2512 
2513   if (!spec_types)
2514     return NULL_TREE;
2515 
2516   if (spec_types == void_list_node)
2517     return void_list_node;
2518 
2519   /* Substitute into the rest of the list.  */
2520   new_spec_types =
2521     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2522 					  TREE_CHAIN (tmpl_types));
2523 
2524   /* Add the default argument for this parameter.  */
2525   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2526 			 TREE_VALUE (spec_types),
2527 			 new_spec_types);
2528 }
2529 
2530 /* DECL is an explicit specialization.  Replicate default arguments
2531    from the template it specializes.  (That way, code like:
2532 
2533      template <class T> void f(T = 3);
2534      template <> void f(double);
2535      void g () { f (); }
2536 
2537    works, as required.)  An alternative approach would be to look up
2538    the correct default arguments at the call-site, but this approach
2539    is consistent with how implicit instantiations are handled.  */
2540 
2541 static void
copy_default_args_to_explicit_spec(tree decl)2542 copy_default_args_to_explicit_spec (tree decl)
2543 {
2544   tree tmpl;
2545   tree spec_types;
2546   tree tmpl_types;
2547   tree new_spec_types;
2548   tree old_type;
2549   tree new_type;
2550   tree t;
2551   tree object_type = NULL_TREE;
2552   tree in_charge = NULL_TREE;
2553   tree vtt = NULL_TREE;
2554 
2555   /* See if there's anything we need to do.  */
2556   tmpl = DECL_TI_TEMPLATE (decl);
2557   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2558   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2559     if (TREE_PURPOSE (t))
2560       break;
2561   if (!t)
2562     return;
2563 
2564   old_type = TREE_TYPE (decl);
2565   spec_types = TYPE_ARG_TYPES (old_type);
2566 
2567   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2568     {
2569       /* Remove the this pointer, but remember the object's type for
2570 	 CV quals.  */
2571       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2572       spec_types = TREE_CHAIN (spec_types);
2573       tmpl_types = TREE_CHAIN (tmpl_types);
2574 
2575       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2576 	{
2577 	  /* DECL may contain more parameters than TMPL due to the extra
2578 	     in-charge parameter in constructors and destructors.  */
2579 	  in_charge = spec_types;
2580 	  spec_types = TREE_CHAIN (spec_types);
2581 	}
2582       if (DECL_HAS_VTT_PARM_P (decl))
2583 	{
2584 	  vtt = spec_types;
2585 	  spec_types = TREE_CHAIN (spec_types);
2586 	}
2587     }
2588 
2589   /* Compute the merged default arguments.  */
2590   new_spec_types =
2591     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2592 
2593   /* Compute the new FUNCTION_TYPE.  */
2594   if (object_type)
2595     {
2596       if (vtt)
2597 	new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2598 					 TREE_VALUE (vtt),
2599 					 new_spec_types);
2600 
2601       if (in_charge)
2602 	/* Put the in-charge parameter back.  */
2603 	new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2604 					 TREE_VALUE (in_charge),
2605 					 new_spec_types);
2606 
2607       new_type = build_method_type_directly (object_type,
2608 					     TREE_TYPE (old_type),
2609 					     new_spec_types);
2610     }
2611   else
2612     new_type = build_function_type (TREE_TYPE (old_type),
2613 				    new_spec_types);
2614   new_type = cp_build_type_attribute_variant (new_type,
2615 					      TYPE_ATTRIBUTES (old_type));
2616   new_type = cxx_copy_lang_qualifiers (new_type, old_type);
2617 
2618   TREE_TYPE (decl) = new_type;
2619 }
2620 
2621 /* Return the number of template headers we expect to see for a definition
2622    or specialization of CTYPE or one of its non-template members.  */
2623 
2624 int
num_template_headers_for_class(tree ctype)2625 num_template_headers_for_class (tree ctype)
2626 {
2627   int num_templates = 0;
2628 
2629   while (ctype && CLASS_TYPE_P (ctype))
2630     {
2631       /* You're supposed to have one `template <...>' for every
2632 	 template class, but you don't need one for a full
2633 	 specialization.  For example:
2634 
2635 	 template <class T> struct S{};
2636 	 template <> struct S<int> { void f(); };
2637 	 void S<int>::f () {}
2638 
2639 	 is correct; there shouldn't be a `template <>' for the
2640 	 definition of `S<int>::f'.  */
2641       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2642 	/* If CTYPE does not have template information of any
2643 	   kind,  then it is not a template, nor is it nested
2644 	   within a template.  */
2645 	break;
2646       if (explicit_class_specialization_p (ctype))
2647 	break;
2648       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2649 	++num_templates;
2650 
2651       ctype = TYPE_CONTEXT (ctype);
2652     }
2653 
2654   return num_templates;
2655 }
2656 
2657 /* Do a simple sanity check on the template headers that precede the
2658    variable declaration DECL.  */
2659 
2660 void
check_template_variable(tree decl)2661 check_template_variable (tree decl)
2662 {
2663   tree ctx = CP_DECL_CONTEXT (decl);
2664   int wanted = num_template_headers_for_class (ctx);
2665   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2666       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2667     {
2668       if (cxx_dialect < cxx14)
2669         pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2670 		 "variable templates only available with "
2671 		 "%<-std=c++14%> or %<-std=gnu++14%>");
2672 
2673       // Namespace-scope variable templates should have a template header.
2674       ++wanted;
2675     }
2676   if (template_header_count > wanted)
2677     {
2678       auto_diagnostic_group d;
2679       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2680 			     "too many template headers for %qD "
2681 	                     "(should be %d)",
2682 			     decl, wanted);
2683       if (warned && CLASS_TYPE_P (ctx)
2684 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2685 	inform (DECL_SOURCE_LOCATION (decl),
2686 		"members of an explicitly specialized class are defined "
2687 		"without a template header");
2688     }
2689 }
2690 
2691 /* An explicit specialization whose declarator-id or class-head-name is not
2692    qualified shall be declared in the nearest enclosing namespace of the
2693    template, or, if the namespace is inline (7.3.1), any namespace from its
2694    enclosing namespace set.
2695 
2696    If the name declared in the explicit instantiation is an unqualified name,
2697    the explicit instantiation shall appear in the namespace where its template
2698    is declared or, if that namespace is inline (7.3.1), any namespace from its
2699    enclosing namespace set.  */
2700 
2701 void
check_unqualified_spec_or_inst(tree t,location_t loc)2702 check_unqualified_spec_or_inst (tree t, location_t loc)
2703 {
2704   tree tmpl = most_general_template (t);
2705   if (DECL_NAMESPACE_SCOPE_P (tmpl)
2706       && !is_nested_namespace (current_namespace,
2707 			       CP_DECL_CONTEXT (tmpl), true))
2708     {
2709       if (processing_specialization)
2710 	permerror (loc, "explicit specialization of %qD outside its "
2711 		   "namespace must use a nested-name-specifier", tmpl);
2712       else if (processing_explicit_instantiation
2713 	       && cxx_dialect >= cxx11)
2714 	/* This was allowed in C++98, so only pedwarn.  */
2715 	pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2716 		 "outside its namespace must use a nested-name-"
2717 		 "specifier", tmpl);
2718     }
2719 }
2720 
2721 /* Warn for a template specialization SPEC that is missing some of a set
2722    of function or type attributes that the template TEMPL is declared with.
2723    ATTRLIST is a list of additional attributes that SPEC should be taken
2724    to ultimately be declared with.  */
2725 
2726 static void
warn_spec_missing_attributes(tree tmpl,tree spec,tree attrlist)2727 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2728 {
2729   if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2730     tmpl = DECL_TEMPLATE_RESULT (tmpl);
2731 
2732   /* Avoid warning if the difference between the primary and
2733      the specialization is not in one of the attributes below.  */
2734   const char* const blacklist[] = {
2735     "alloc_align", "alloc_size", "assume_aligned", "format",
2736     "format_arg", "malloc", "nonnull", NULL
2737   };
2738 
2739   /* Put together a list of the black listed attributes that the primary
2740      template is declared with that the specialization is not, in case
2741      it's not apparent from the most recent declaration of the primary.  */
2742   pretty_printer str;
2743   unsigned nattrs = decls_mismatched_attributes (tmpl, spec, attrlist,
2744 						 blacklist, &str);
2745 
2746   if (!nattrs)
2747     return;
2748 
2749   auto_diagnostic_group d;
2750   if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2751 		  "explicit specialization %q#D may be missing attributes",
2752 		  spec))
2753     inform (DECL_SOURCE_LOCATION (tmpl),
2754 	    nattrs > 1
2755 	    ? G_("missing primary template attributes %s")
2756 	    : G_("missing primary template attribute %s"),
2757 	    pp_formatted_text (&str));
2758 }
2759 
2760 /* Check to see if the function just declared, as indicated in
2761    DECLARATOR, and in DECL, is a specialization of a function
2762    template.  We may also discover that the declaration is an explicit
2763    instantiation at this point.
2764 
2765    Returns DECL, or an equivalent declaration that should be used
2766    instead if all goes well.  Issues an error message if something is
2767    amiss.  Returns error_mark_node if the error is not easily
2768    recoverable.
2769 
2770    FLAGS is a bitmask consisting of the following flags:
2771 
2772    2: The function has a definition.
2773    4: The function is a friend.
2774 
2775    The TEMPLATE_COUNT is the number of references to qualifying
2776    template classes that appeared in the name of the function.  For
2777    example, in
2778 
2779      template <class T> struct S { void f(); };
2780      void S<int>::f();
2781 
2782    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2783    classes are not counted in the TEMPLATE_COUNT, so that in
2784 
2785      template <class T> struct S {};
2786      template <> struct S<int> { void f(); }
2787      template <> void S<int>::f();
2788 
2789    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2790    invalid; there should be no template <>.)
2791 
2792    If the function is a specialization, it is marked as such via
2793    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2794    is set up correctly, and it is added to the list of specializations
2795    for that template.  */
2796 
2797 tree
check_explicit_specialization(tree declarator,tree decl,int template_count,int flags,tree attrlist)2798 check_explicit_specialization (tree declarator,
2799 			       tree decl,
2800 			       int template_count,
2801 			       int flags,
2802 			       tree attrlist)
2803 {
2804   int have_def = flags & 2;
2805   int is_friend = flags & 4;
2806   bool is_concept = flags & 8;
2807   int specialization = 0;
2808   int explicit_instantiation = 0;
2809   int member_specialization = 0;
2810   tree ctype = DECL_CLASS_CONTEXT (decl);
2811   tree dname = DECL_NAME (decl);
2812   tmpl_spec_kind tsk;
2813 
2814   if (is_friend)
2815     {
2816       if (!processing_specialization)
2817 	tsk = tsk_none;
2818       else
2819 	tsk = tsk_excessive_parms;
2820     }
2821   else
2822     tsk = current_tmpl_spec_kind (template_count);
2823 
2824   switch (tsk)
2825     {
2826     case tsk_none:
2827       if (processing_specialization && !VAR_P (decl))
2828 	{
2829 	  specialization = 1;
2830 	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2831 	}
2832       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2833 	{
2834 	  if (is_friend)
2835 	    /* This could be something like:
2836 
2837 	       template <class T> void f(T);
2838 	       class S { friend void f<>(int); }  */
2839 	    specialization = 1;
2840 	  else
2841 	    {
2842 	      /* This case handles bogus declarations like template <>
2843 		 template <class T> void f<int>(); */
2844 
2845 	      error_at (cp_expr_loc_or_input_loc (declarator),
2846 			"template-id %qE in declaration of primary template",
2847 			declarator);
2848 	      return decl;
2849 	    }
2850 	}
2851       break;
2852 
2853     case tsk_invalid_member_spec:
2854       /* The error has already been reported in
2855 	 check_specialization_scope.  */
2856       return error_mark_node;
2857 
2858     case tsk_invalid_expl_inst:
2859       error ("template parameter list used in explicit instantiation");
2860 
2861       /* Fall through.  */
2862 
2863     case tsk_expl_inst:
2864       if (have_def)
2865 	error ("definition provided for explicit instantiation");
2866 
2867       explicit_instantiation = 1;
2868       break;
2869 
2870     case tsk_excessive_parms:
2871     case tsk_insufficient_parms:
2872       if (tsk == tsk_excessive_parms)
2873 	error ("too many template parameter lists in declaration of %qD",
2874 	       decl);
2875       else if (template_header_count)
2876 	error("too few template parameter lists in declaration of %qD", decl);
2877       else
2878 	error("explicit specialization of %qD must be introduced by "
2879 	      "%<template <>%>", decl);
2880 
2881       /* Fall through.  */
2882     case tsk_expl_spec:
2883       if (is_concept)
2884         error ("explicit specialization declared %<concept%>");
2885 
2886       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2887 	/* In cases like template<> constexpr bool v = true;
2888 	   We'll give an error in check_template_variable.  */
2889 	break;
2890 
2891       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2892       if (ctype)
2893 	member_specialization = 1;
2894       else
2895 	specialization = 1;
2896       break;
2897 
2898     case tsk_template:
2899       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2900 	{
2901 	  /* This case handles bogus declarations like template <>
2902 	     template <class T> void f<int>(); */
2903 
2904 	  if (!uses_template_parms (TREE_OPERAND (declarator, 1)))
2905 	    error_at (cp_expr_loc_or_input_loc (declarator),
2906 		      "template-id %qE in declaration of primary template",
2907 		      declarator);
2908 	  else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2909 	    {
2910 	      /* Partial specialization of variable template.  */
2911 	      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2912 	      specialization = 1;
2913 	      goto ok;
2914 	    }
2915 	  else if (cxx_dialect < cxx14)
2916 	    error_at (cp_expr_loc_or_input_loc (declarator),
2917 		      "non-type partial specialization %qE "
2918 		      "is not allowed", declarator);
2919 	  else
2920 	    error_at (cp_expr_loc_or_input_loc (declarator),
2921 		      "non-class, non-variable partial specialization %qE "
2922 		      "is not allowed", declarator);
2923 	  return decl;
2924 	ok:;
2925 	}
2926 
2927       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2928 	/* This is a specialization of a member template, without
2929 	   specialization the containing class.  Something like:
2930 
2931 	     template <class T> struct S {
2932 	       template <class U> void f (U);
2933 	     };
2934 	     template <> template <class U> void S<int>::f(U) {}
2935 
2936 	   That's a specialization -- but of the entire template.  */
2937 	specialization = 1;
2938       break;
2939 
2940     default:
2941       gcc_unreachable ();
2942     }
2943 
2944   if ((specialization || member_specialization)
2945       /* This doesn't apply to variable templates.  */
2946       && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (decl)))
2947     {
2948       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2949       for (; t; t = TREE_CHAIN (t))
2950 	if (TREE_PURPOSE (t))
2951 	  {
2952 	    permerror (input_location,
2953 		       "default argument specified in explicit specialization");
2954 	    break;
2955 	  }
2956     }
2957 
2958   if (specialization || member_specialization || explicit_instantiation)
2959     {
2960       tree tmpl = NULL_TREE;
2961       tree targs = NULL_TREE;
2962       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2963 
2964       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2965       if (!was_template_id)
2966 	{
2967 	  tree fns;
2968 
2969 	  gcc_assert (identifier_p (declarator));
2970 	  if (ctype)
2971 	    fns = dname;
2972 	  else
2973 	    {
2974 	      /* If there is no class context, the explicit instantiation
2975 		 must be at namespace scope.  */
2976 	      gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2977 
2978 	      /* Find the namespace binding, using the declaration
2979 		 context.  */
2980 	      fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2981 					   false, true);
2982 	      if (fns == error_mark_node)
2983 		/* If lookup fails, look for a friend declaration so we can
2984 		   give a better diagnostic.  */
2985 		fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2986 					     /*type*/false, /*complain*/true,
2987 					     /*hidden*/true);
2988 
2989 	      if (fns == error_mark_node || !is_overloaded_fn (fns))
2990 		{
2991 		  error ("%qD is not a template function", dname);
2992 		  fns = error_mark_node;
2993 		}
2994 	    }
2995 
2996 	  declarator = lookup_template_function (fns, NULL_TREE);
2997 	}
2998 
2999       if (declarator == error_mark_node)
3000 	return error_mark_node;
3001 
3002       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
3003 	{
3004 	  if (!explicit_instantiation)
3005 	    /* A specialization in class scope.  This is invalid,
3006 	       but the error will already have been flagged by
3007 	       check_specialization_scope.  */
3008 	    return error_mark_node;
3009 	  else
3010 	    {
3011 	      /* It's not valid to write an explicit instantiation in
3012 		 class scope, e.g.:
3013 
3014 		   class C { template void f(); }
3015 
3016 		   This case is caught by the parser.  However, on
3017 		   something like:
3018 
3019 		   template class C { void f(); };
3020 
3021 		   (which is invalid) we can get here.  The error will be
3022 		   issued later.  */
3023 	      ;
3024 	    }
3025 
3026 	  return decl;
3027 	}
3028       else if (ctype != NULL_TREE
3029 	       && (identifier_p (TREE_OPERAND (declarator, 0))))
3030 	{
3031 	  // We'll match variable templates in start_decl.
3032 	  if (VAR_P (decl))
3033 	    return decl;
3034 
3035 	  /* Find the list of functions in ctype that have the same
3036 	     name as the declared function.  */
3037 	  tree name = TREE_OPERAND (declarator, 0);
3038 
3039 	  if (constructor_name_p (name, ctype))
3040 	    {
3041 	      if (DECL_CONSTRUCTOR_P (decl)
3042 		  ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3043 		  : !CLASSTYPE_DESTRUCTOR (ctype))
3044 		{
3045 		  /* From [temp.expl.spec]:
3046 
3047 		     If such an explicit specialization for the member
3048 		     of a class template names an implicitly-declared
3049 		     special member function (clause _special_), the
3050 		     program is ill-formed.
3051 
3052 		     Similar language is found in [temp.explicit].  */
3053 		  error ("specialization of implicitly-declared special member function");
3054 		  return error_mark_node;
3055 		}
3056 
3057 	      name = DECL_NAME (decl);
3058 	    }
3059 
3060 	  /* For a type-conversion operator, We might be looking for
3061 	     `operator int' which will be a specialization of
3062 	     `operator T'.  Grab all the conversion operators, and
3063 	     then select from them.  */
3064 	  tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3065 					? conv_op_identifier : name);
3066 
3067 	  if (fns == NULL_TREE)
3068 	    {
3069 	      error ("no member function %qD declared in %qT", name, ctype);
3070 	      return error_mark_node;
3071 	    }
3072 	  else
3073 	    TREE_OPERAND (declarator, 0) = fns;
3074 	}
3075 
3076       /* Figure out what exactly is being specialized at this point.
3077 	 Note that for an explicit instantiation, even one for a
3078 	 member function, we cannot tell a priori whether the
3079 	 instantiation is for a member template, or just a member
3080 	 function of a template class.  Even if a member template is
3081 	 being instantiated, the member template arguments may be
3082 	 elided if they can be deduced from the rest of the
3083 	 declaration.  */
3084       tmpl = determine_specialization (declarator, decl,
3085 				       &targs,
3086 				       member_specialization,
3087 				       template_count,
3088 				       tsk);
3089 
3090       if (!tmpl || tmpl == error_mark_node)
3091 	/* We couldn't figure out what this declaration was
3092 	   specializing.  */
3093 	return error_mark_node;
3094       else
3095 	{
3096 	  if (TREE_CODE (decl) == FUNCTION_DECL
3097 	      && DECL_HIDDEN_FRIEND_P (tmpl))
3098 	    {
3099 	      auto_diagnostic_group d;
3100 	      if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3101 			   "friend declaration %qD is not visible to "
3102 			   "explicit specialization", tmpl))
3103 		inform (DECL_SOURCE_LOCATION (tmpl),
3104 			"friend declaration here");
3105 	    }
3106 	  else if (!ctype && !is_friend
3107 		   && CP_DECL_CONTEXT (decl) == current_namespace)
3108 	    check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3109 
3110 	  tree gen_tmpl = most_general_template (tmpl);
3111 
3112 	  if (explicit_instantiation)
3113 	    {
3114 	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3115 		 is done by do_decl_instantiation later.  */
3116 
3117 	      int arg_depth = TMPL_ARGS_DEPTH (targs);
3118 	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3119 
3120 	      if (arg_depth > parm_depth)
3121 		{
3122 		  /* If TMPL is not the most general template (for
3123 		     example, if TMPL is a friend template that is
3124 		     injected into namespace scope), then there will
3125 		     be too many levels of TARGS.  Remove some of them
3126 		     here.  */
3127 		  int i;
3128 		  tree new_targs;
3129 
3130 		  new_targs = make_tree_vec (parm_depth);
3131 		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3132 		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3133 		      = TREE_VEC_ELT (targs, i);
3134 		  targs = new_targs;
3135 		}
3136 
3137 	      return instantiate_template (tmpl, targs, tf_error);
3138 	    }
3139 
3140 	  /* If we thought that the DECL was a member function, but it
3141 	     turns out to be specializing a static member function,
3142 	     make DECL a static member function as well.  */
3143 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3144 	      && DECL_STATIC_FUNCTION_P (tmpl)
3145 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3146 	    revert_static_member_fn (decl);
3147 
3148 	  /* If this is a specialization of a member template of a
3149 	     template class, we want to return the TEMPLATE_DECL, not
3150 	     the specialization of it.  */
3151 	  if (tsk == tsk_template && !was_template_id)
3152 	    {
3153 	      tree result = DECL_TEMPLATE_RESULT (tmpl);
3154 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3155 	      DECL_INITIAL (result) = NULL_TREE;
3156 	      if (have_def)
3157 		{
3158 		  tree parm;
3159 		  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3160 		  DECL_SOURCE_LOCATION (result)
3161 		    = DECL_SOURCE_LOCATION (decl);
3162 		  /* We want to use the argument list specified in the
3163 		     definition, not in the original declaration.  */
3164 		  DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3165 		  for (parm = DECL_ARGUMENTS (result); parm;
3166 		       parm = DECL_CHAIN (parm))
3167 		    DECL_CONTEXT (parm) = result;
3168 		}
3169 	      return register_specialization (tmpl, gen_tmpl, targs,
3170 					      is_friend, 0);
3171 	    }
3172 
3173 	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
3174 	  DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3175 
3176 	  if (was_template_id)
3177 	    TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3178 
3179 	  /* Inherit default function arguments from the template
3180 	     DECL is specializing.  */
3181 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3182 	    copy_default_args_to_explicit_spec (decl);
3183 
3184 	  /* This specialization has the same protection as the
3185 	     template it specializes.  */
3186 	  TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3187 	  TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3188 
3189           /* 7.1.1-1 [dcl.stc]
3190 
3191              A storage-class-specifier shall not be specified in an
3192              explicit specialization...
3193 
3194              The parser rejects these, so unless action is taken here,
3195              explicit function specializations will always appear with
3196              global linkage.
3197 
3198              The action recommended by the C++ CWG in response to C++
3199              defect report 605 is to make the storage class and linkage
3200              of the explicit specialization match the templated function:
3201 
3202              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3203            */
3204           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3205             {
3206               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3207               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3208 
3209               /* A concept cannot be specialized.  */
3210               if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3211                 {
3212                   error ("explicit specialization of function concept %qD",
3213                          gen_tmpl);
3214                   return error_mark_node;
3215                 }
3216 
3217               /* This specialization has the same linkage and visibility as
3218                  the function template it specializes.  */
3219               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3220 	      if (! TREE_PUBLIC (decl))
3221 		{
3222 		  DECL_INTERFACE_KNOWN (decl) = 1;
3223 		  DECL_NOT_REALLY_EXTERN (decl) = 1;
3224 		}
3225               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3226               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3227                 {
3228                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
3229                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3230                 }
3231             }
3232 
3233 	  /* If DECL is a friend declaration, declared using an
3234 	     unqualified name, the namespace associated with DECL may
3235 	     have been set incorrectly.  For example, in:
3236 
3237 	       template <typename T> void f(T);
3238 	       namespace N {
3239 		 struct S { friend void f<int>(int); }
3240 	       }
3241 
3242 	     we will have set the DECL_CONTEXT for the friend
3243 	     declaration to N, rather than to the global namespace.  */
3244 	  if (DECL_NAMESPACE_SCOPE_P (decl))
3245 	    DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3246 
3247 	  if (is_friend && !have_def)
3248 	    /* This is not really a declaration of a specialization.
3249 	       It's just the name of an instantiation.  But, it's not
3250 	       a request for an instantiation, either.  */
3251 	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
3252 	  else if (TREE_CODE (decl) == FUNCTION_DECL)
3253 	    /* A specialization is not necessarily COMDAT.  */
3254 	    DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3255 				  && DECL_DECLARED_INLINE_P (decl));
3256 	  else if (VAR_P (decl))
3257 	    DECL_COMDAT (decl) = false;
3258 
3259 	  /* If this is a full specialization, register it so that we can find
3260 	     it again.  Partial specializations will be registered in
3261 	     process_partial_specialization.  */
3262 	  if (!processing_template_decl)
3263 	    {
3264 	      warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3265 
3266 	      decl = register_specialization (decl, gen_tmpl, targs,
3267 					      is_friend, 0);
3268 	    }
3269 
3270 
3271 	  /* A 'structor should already have clones.  */
3272 	  gcc_assert (decl == error_mark_node
3273 		      || variable_template_p (tmpl)
3274 		      || !(DECL_CONSTRUCTOR_P (decl)
3275 			   || DECL_DESTRUCTOR_P (decl))
3276 		      || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3277 	}
3278     }
3279 
3280   return decl;
3281 }
3282 
3283 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3284    parameters.  These are represented in the same format used for
3285    DECL_TEMPLATE_PARMS.  */
3286 
3287 int
comp_template_parms(const_tree parms1,const_tree parms2)3288 comp_template_parms (const_tree parms1, const_tree parms2)
3289 {
3290   const_tree p1;
3291   const_tree p2;
3292 
3293   if (parms1 == parms2)
3294     return 1;
3295 
3296   for (p1 = parms1, p2 = parms2;
3297        p1 != NULL_TREE && p2 != NULL_TREE;
3298        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3299     {
3300       tree t1 = TREE_VALUE (p1);
3301       tree t2 = TREE_VALUE (p2);
3302       int i;
3303 
3304       gcc_assert (TREE_CODE (t1) == TREE_VEC);
3305       gcc_assert (TREE_CODE (t2) == TREE_VEC);
3306 
3307       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3308 	return 0;
3309 
3310       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3311 	{
3312           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3313           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3314 
3315           /* If either of the template parameters are invalid, assume
3316              they match for the sake of error recovery. */
3317           if (error_operand_p (parm1) || error_operand_p (parm2))
3318             return 1;
3319 
3320 	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
3321 	    return 0;
3322 
3323 	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3324               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3325                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3326 	    continue;
3327 	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3328 	    return 0;
3329 	}
3330     }
3331 
3332   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3333     /* One set of parameters has more parameters lists than the
3334        other.  */
3335     return 0;
3336 
3337   return 1;
3338 }
3339 
3340 /* Returns true if two template parameters are declared with
3341    equivalent constraints.  */
3342 
3343 static bool
template_parameter_constraints_equivalent_p(const_tree parm1,const_tree parm2)3344 template_parameter_constraints_equivalent_p (const_tree parm1, const_tree parm2)
3345 {
3346   tree req1 = TREE_TYPE (parm1);
3347   tree req2 = TREE_TYPE (parm2);
3348   if (!req1 != !req2)
3349     return false;
3350   if (req1)
3351     return cp_tree_equal (req1, req2);
3352   return true;
3353 }
3354 
3355 /* Returns true when two template parameters are equivalent.  */
3356 
3357 static bool
template_parameters_equivalent_p(const_tree parm1,const_tree parm2)3358 template_parameters_equivalent_p (const_tree parm1, const_tree parm2)
3359 {
3360   tree decl1 = TREE_VALUE (parm1);
3361   tree decl2 = TREE_VALUE (parm2);
3362 
3363   /* If either of the template parameters are invalid, assume
3364      they match for the sake of error recovery. */
3365   if (error_operand_p (decl1) || error_operand_p (decl2))
3366     return true;
3367 
3368   /* ... they declare parameters of the same kind.  */
3369   if (TREE_CODE (decl1) != TREE_CODE (decl2))
3370     return false;
3371 
3372   /* ... one parameter was introduced by a parameter declaration, then
3373      both are. This case arises as a result of eagerly rewriting declarations
3374      during parsing.  */
3375   if (DECL_VIRTUAL_P (decl1) != DECL_VIRTUAL_P (decl2))
3376     return false;
3377 
3378   /* ... if either declares a pack, they both do.  */
3379   if (template_parameter_pack_p (decl1) != template_parameter_pack_p (decl2))
3380     return false;
3381 
3382   if (TREE_CODE (decl1) == PARM_DECL)
3383     {
3384       /* ... if they declare non-type parameters, the types are equivalent.  */
3385       if (!same_type_p (TREE_TYPE (decl1), TREE_TYPE (decl2)))
3386 	return false;
3387     }
3388   else if (TREE_CODE (decl2) == TEMPLATE_DECL)
3389     {
3390       /* ... if they declare template template parameters, their template
3391 	 parameter lists are equivalent.  */
3392       if (!template_heads_equivalent_p (decl1, decl2))
3393 	return false;
3394     }
3395 
3396   /* ... if they are declared with a qualified-concept name, they both
3397      are, and those names are equivalent.  */
3398   return template_parameter_constraints_equivalent_p (parm1, parm2);
3399 }
3400 
3401 /* Returns true if two template parameters lists are equivalent.
3402    Two template parameter lists are equivalent if they have the
3403    same length and their corresponding parameters are equivalent.
3404 
3405    PARMS1 and PARMS2 are TREE_LISTs containing TREE_VECs: the
3406    data structure returned by DECL_TEMPLATE_PARMS.
3407 
3408    This is generally the same implementation as comp_template_parms
3409    except that it also the concept names and arguments used to
3410    introduce parameters.  */
3411 
3412 static bool
template_parameter_lists_equivalent_p(const_tree parms1,const_tree parms2)3413 template_parameter_lists_equivalent_p (const_tree parms1, const_tree parms2)
3414 {
3415   if (parms1 == parms2)
3416     return true;
3417 
3418   const_tree p1 = parms1;
3419   const_tree p2 = parms2;
3420   while (p1 != NULL_TREE && p2 != NULL_TREE)
3421     {
3422       tree list1 = TREE_VALUE (p1);
3423       tree list2 = TREE_VALUE (p2);
3424 
3425       if (TREE_VEC_LENGTH (list1) != TREE_VEC_LENGTH (list2))
3426 	return 0;
3427 
3428       for (int i = 0; i < TREE_VEC_LENGTH (list2); ++i)
3429 	{
3430 	  tree parm1 = TREE_VEC_ELT (list1, i);
3431 	  tree parm2 = TREE_VEC_ELT (list2, i);
3432 	  if (!template_parameters_equivalent_p (parm1, parm2))
3433 	    return false;
3434 	}
3435 
3436       p1 = TREE_CHAIN (p1);
3437       p2 = TREE_CHAIN (p2);
3438     }
3439 
3440   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3441     return false;
3442 
3443   return true;
3444 }
3445 
3446 /* Return true if the requires-clause of the template parameter lists are
3447    equivalent and false otherwise.  */
3448 static bool
template_requirements_equivalent_p(const_tree parms1,const_tree parms2)3449 template_requirements_equivalent_p (const_tree parms1, const_tree parms2)
3450 {
3451   tree req1 = TEMPLATE_PARMS_CONSTRAINTS (parms1);
3452   tree req2 = TEMPLATE_PARMS_CONSTRAINTS (parms2);
3453   if ((req1 != NULL_TREE) != (req2 != NULL_TREE))
3454     return false;
3455   if (!cp_tree_equal (req1, req2))
3456     return false;
3457   return true;
3458 }
3459 
3460 /* Returns true if two template heads are equivalent. 17.6.6.1p6:
3461    Two template heads are equivalent if their template parameter
3462    lists are equivalent and their requires clauses are equivalent.
3463 
3464    In pre-C++20, this is equivalent to calling comp_template_parms
3465    for the template parameters of TMPL1 and TMPL2.  */
3466 
3467 bool
template_heads_equivalent_p(const_tree tmpl1,const_tree tmpl2)3468 template_heads_equivalent_p (const_tree tmpl1, const_tree tmpl2)
3469 {
3470   tree parms1 = DECL_TEMPLATE_PARMS (tmpl1);
3471   tree parms2 = DECL_TEMPLATE_PARMS (tmpl2);
3472 
3473   /* Don't change the matching rules for pre-C++20.  */
3474   if (cxx_dialect < cxx2a)
3475     return comp_template_parms (parms1, parms2);
3476 
3477   /* ... have the same number of template parameters, and their
3478      corresponding parameters are equivalent.  */
3479   if (!template_parameter_lists_equivalent_p (parms1, parms2))
3480     return false;
3481 
3482   /* ... if either has a requires-clause, they both do and their
3483      corresponding constraint-expressions are equivalent.  */
3484   return template_requirements_equivalent_p (parms1, parms2);
3485 }
3486 
3487 /* Determine whether PARM is a parameter pack.  */
3488 
3489 bool
template_parameter_pack_p(const_tree parm)3490 template_parameter_pack_p (const_tree parm)
3491 {
3492   /* Determine if we have a non-type template parameter pack.  */
3493   if (TREE_CODE (parm) == PARM_DECL)
3494     return (DECL_TEMPLATE_PARM_P (parm)
3495             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3496   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3497     return TEMPLATE_PARM_PARAMETER_PACK (parm);
3498 
3499   /* If this is a list of template parameters, we could get a
3500      TYPE_DECL or a TEMPLATE_DECL.  */
3501   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3502     parm = TREE_TYPE (parm);
3503 
3504   /* Otherwise it must be a type template parameter.  */
3505   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3506 	   || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3507 	  && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3508 }
3509 
3510 /* Determine if T is a function parameter pack.  */
3511 
3512 bool
function_parameter_pack_p(const_tree t)3513 function_parameter_pack_p (const_tree t)
3514 {
3515   if (t && TREE_CODE (t) == PARM_DECL)
3516     return DECL_PACK_P (t);
3517   return false;
3518 }
3519 
3520 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3521    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
3522 
3523 tree
get_function_template_decl(const_tree primary_func_tmpl_inst)3524 get_function_template_decl (const_tree primary_func_tmpl_inst)
3525 {
3526   if (! primary_func_tmpl_inst
3527       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3528       || ! primary_template_specialization_p (primary_func_tmpl_inst))
3529     return NULL;
3530 
3531   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3532 }
3533 
3534 /* Return true iff the function parameter PARAM_DECL was expanded
3535    from the function parameter pack PACK.  */
3536 
3537 bool
function_parameter_expanded_from_pack_p(tree param_decl,tree pack)3538 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3539 {
3540   if (DECL_ARTIFICIAL (param_decl)
3541       || !function_parameter_pack_p (pack))
3542     return false;
3543 
3544   /* The parameter pack and its pack arguments have the same
3545      DECL_PARM_INDEX.  */
3546   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3547 }
3548 
3549 /* Determine whether ARGS describes a variadic template args list,
3550    i.e., one that is terminated by a template argument pack.  */
3551 
3552 static bool
template_args_variadic_p(tree args)3553 template_args_variadic_p (tree args)
3554 {
3555   int nargs;
3556   tree last_parm;
3557 
3558   if (args == NULL_TREE)
3559     return false;
3560 
3561   args = INNERMOST_TEMPLATE_ARGS (args);
3562   nargs = TREE_VEC_LENGTH (args);
3563 
3564   if (nargs == 0)
3565     return false;
3566 
3567   last_parm = TREE_VEC_ELT (args, nargs - 1);
3568 
3569   return ARGUMENT_PACK_P (last_parm);
3570 }
3571 
3572 /* Generate a new name for the parameter pack name NAME (an
3573    IDENTIFIER_NODE) that incorporates its */
3574 
3575 static tree
make_ith_pack_parameter_name(tree name,int i)3576 make_ith_pack_parameter_name (tree name, int i)
3577 {
3578   /* Munge the name to include the parameter index.  */
3579 #define NUMBUF_LEN 128
3580   char numbuf[NUMBUF_LEN];
3581   char* newname;
3582   int newname_len;
3583 
3584   if (name == NULL_TREE)
3585     return name;
3586   snprintf (numbuf, NUMBUF_LEN, "%i", i);
3587   newname_len = IDENTIFIER_LENGTH (name)
3588 	        + strlen (numbuf) + 2;
3589   newname = (char*)alloca (newname_len);
3590   snprintf (newname, newname_len,
3591 	    "%s#%i", IDENTIFIER_POINTER (name), i);
3592   return get_identifier (newname);
3593 }
3594 
3595 /* Return true if T is a primary function, class or alias template
3596    specialization, not including the template pattern.  */
3597 
3598 bool
primary_template_specialization_p(const_tree t)3599 primary_template_specialization_p (const_tree t)
3600 {
3601   if (!t)
3602     return false;
3603 
3604   if (TREE_CODE (t) == FUNCTION_DECL || VAR_P (t))
3605     return (DECL_LANG_SPECIFIC (t)
3606 	    && DECL_USE_TEMPLATE (t)
3607 	    && DECL_TEMPLATE_INFO (t)
3608 	    && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3609   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3610     return (CLASSTYPE_TEMPLATE_INFO (t)
3611 	    && CLASSTYPE_USE_TEMPLATE (t)
3612 	    && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3613   else if (alias_template_specialization_p (t, nt_transparent))
3614     return true;
3615   return false;
3616 }
3617 
3618 /* Return true if PARM is a template template parameter.  */
3619 
3620 bool
template_template_parameter_p(const_tree parm)3621 template_template_parameter_p (const_tree parm)
3622 {
3623   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3624 }
3625 
3626 /* Return true iff PARM is a DECL representing a type template
3627    parameter.  */
3628 
3629 bool
template_type_parameter_p(const_tree parm)3630 template_type_parameter_p (const_tree parm)
3631 {
3632   return (parm
3633 	  && (TREE_CODE (parm) == TYPE_DECL
3634 	      || TREE_CODE (parm) == TEMPLATE_DECL)
3635 	  && DECL_TEMPLATE_PARM_P (parm));
3636 }
3637 
3638 /* Return the template parameters of T if T is a
3639    primary template instantiation, NULL otherwise.  */
3640 
3641 tree
get_primary_template_innermost_parameters(const_tree t)3642 get_primary_template_innermost_parameters (const_tree t)
3643 {
3644   tree parms = NULL, template_info = NULL;
3645 
3646   if ((template_info = get_template_info (t))
3647       && primary_template_specialization_p (t))
3648     parms = INNERMOST_TEMPLATE_PARMS
3649 	(DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3650 
3651   return parms;
3652 }
3653 
3654 /* Return the template parameters of the LEVELth level from the full list
3655    of template parameters PARMS.  */
3656 
3657 tree
get_template_parms_at_level(tree parms,int level)3658 get_template_parms_at_level (tree parms, int level)
3659 {
3660   tree p;
3661   if (!parms
3662       || TREE_CODE (parms) != TREE_LIST
3663       || level > TMPL_PARMS_DEPTH (parms))
3664     return NULL_TREE;
3665 
3666   for (p = parms; p; p = TREE_CHAIN (p))
3667     if (TMPL_PARMS_DEPTH (p) == level)
3668       return p;
3669 
3670   return NULL_TREE;
3671 }
3672 
3673 /* Returns the template arguments of T if T is a template instantiation,
3674    NULL otherwise.  */
3675 
3676 tree
get_template_innermost_arguments(const_tree t)3677 get_template_innermost_arguments (const_tree t)
3678 {
3679   tree args = NULL, template_info = NULL;
3680 
3681   if ((template_info = get_template_info (t))
3682       && TI_ARGS (template_info))
3683     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3684 
3685   return args;
3686 }
3687 
3688 /* Return the argument pack elements of T if T is a template argument pack,
3689    NULL otherwise.  */
3690 
3691 tree
get_template_argument_pack_elems(const_tree t)3692 get_template_argument_pack_elems (const_tree t)
3693 {
3694   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3695       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3696     return NULL;
3697 
3698   return ARGUMENT_PACK_ARGS (t);
3699 }
3700 
3701 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3702    ARGUMENT_PACK_SELECT represents. */
3703 
3704 static tree
argument_pack_select_arg(tree t)3705 argument_pack_select_arg (tree t)
3706 {
3707   tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3708   tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3709 
3710   /* If the selected argument is an expansion E, that most likely means we were
3711      called from gen_elem_of_pack_expansion_instantiation during the
3712      substituting of an argument pack (of which the Ith element is a pack
3713      expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3714      In this case, the Ith element resulting from this substituting is going to
3715      be a pack expansion, which pattern is the pattern of E.  Let's return the
3716      pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3717      resulting pack expansion from it.  */
3718   if (PACK_EXPANSION_P (arg))
3719     {
3720       /* Make sure we aren't throwing away arg info.  */
3721       gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3722       arg = PACK_EXPANSION_PATTERN (arg);
3723     }
3724 
3725   return arg;
3726 }
3727 
3728 
3729 /* True iff FN is a function representing a built-in variadic parameter
3730    pack.  */
3731 
3732 bool
builtin_pack_fn_p(tree fn)3733 builtin_pack_fn_p (tree fn)
3734 {
3735   if (!fn
3736       || TREE_CODE (fn) != FUNCTION_DECL
3737       || !DECL_IS_BUILTIN (fn))
3738     return false;
3739 
3740   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3741     return true;
3742 
3743   return false;
3744 }
3745 
3746 /* True iff CALL is a call to a function representing a built-in variadic
3747    parameter pack.  */
3748 
3749 static bool
builtin_pack_call_p(tree call)3750 builtin_pack_call_p (tree call)
3751 {
3752   if (TREE_CODE (call) != CALL_EXPR)
3753     return false;
3754   return builtin_pack_fn_p (CALL_EXPR_FN (call));
3755 }
3756 
3757 /* Return a TREE_VEC for the expansion of __integer_pack(HI).  */
3758 
3759 static tree
expand_integer_pack(tree call,tree args,tsubst_flags_t complain,tree in_decl)3760 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3761 		     tree in_decl)
3762 {
3763   tree ohi = CALL_EXPR_ARG (call, 0);
3764   tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3765 				   false/*fn*/, true/*int_cst*/);
3766 
3767   if (value_dependent_expression_p (hi))
3768     {
3769       if (hi != ohi)
3770 	{
3771 	  call = copy_node (call);
3772 	  CALL_EXPR_ARG (call, 0) = hi;
3773 	}
3774       tree ex = make_pack_expansion (call, complain);
3775       tree vec = make_tree_vec (1);
3776       TREE_VEC_ELT (vec, 0) = ex;
3777       return vec;
3778     }
3779   else
3780     {
3781       hi = cxx_constant_value (hi);
3782       int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3783 
3784       /* Calculate the largest value of len that won't make the size of the vec
3785 	 overflow an int.  The compiler will exceed resource limits long before
3786 	 this, but it seems a decent place to diagnose.  */
3787       int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3788 
3789       if (len < 0 || len > max)
3790 	{
3791 	  if ((complain & tf_error)
3792 	      && hi != error_mark_node)
3793 	    error ("argument to %<__integer_pack%> must be between 0 and %d",
3794 		   max);
3795 	  return error_mark_node;
3796 	}
3797 
3798       tree vec = make_tree_vec (len);
3799 
3800       for (int i = 0; i < len; ++i)
3801 	TREE_VEC_ELT (vec, i) = size_int (i);
3802 
3803       return vec;
3804     }
3805 }
3806 
3807 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3808    CALL.  */
3809 
3810 static tree
expand_builtin_pack_call(tree call,tree args,tsubst_flags_t complain,tree in_decl)3811 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3812 			  tree in_decl)
3813 {
3814   if (!builtin_pack_call_p (call))
3815     return NULL_TREE;
3816 
3817   tree fn = CALL_EXPR_FN (call);
3818 
3819   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3820     return expand_integer_pack (call, args, complain, in_decl);
3821 
3822   return NULL_TREE;
3823 }
3824 
3825 /* Structure used to track the progress of find_parameter_packs_r.  */
3826 struct find_parameter_pack_data
3827 {
3828   /* TREE_LIST that will contain all of the parameter packs found by
3829      the traversal.  */
3830   tree* parameter_packs;
3831 
3832   /* Set of AST nodes that have been visited by the traversal.  */
3833   hash_set<tree> *visited;
3834 
3835   /* True iff we're making a type pack expansion.  */
3836   bool type_pack_expansion_p;
3837 };
3838 
3839 /* Identifies all of the argument packs that occur in a template
3840    argument and appends them to the TREE_LIST inside DATA, which is a
3841    find_parameter_pack_data structure. This is a subroutine of
3842    make_pack_expansion and uses_parameter_packs.  */
3843 static tree
find_parameter_packs_r(tree * tp,int * walk_subtrees,void * data)3844 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3845 {
3846   tree t = *tp;
3847   struct find_parameter_pack_data* ppd =
3848     (struct find_parameter_pack_data*)data;
3849   bool parameter_pack_p = false;
3850 
3851   /* Don't look through typedefs; we are interested in whether a
3852      parameter pack is actually written in the expression/type we're
3853      looking at, not the target type.  */
3854   if (TYPE_P (t) && typedef_variant_p (t))
3855     {
3856       /* But do look at arguments for an alias template.  */
3857       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3858 	cp_walk_tree (&TI_ARGS (tinfo),
3859 		      &find_parameter_packs_r,
3860 		      ppd, ppd->visited);
3861       *walk_subtrees = 0;
3862       return NULL_TREE;
3863     }
3864 
3865   /* Identify whether this is a parameter pack or not.  */
3866   switch (TREE_CODE (t))
3867     {
3868     case TEMPLATE_PARM_INDEX:
3869       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3870         parameter_pack_p = true;
3871       break;
3872 
3873     case TEMPLATE_TYPE_PARM:
3874       t = TYPE_MAIN_VARIANT (t);
3875       /* FALLTHRU */
3876     case TEMPLATE_TEMPLATE_PARM:
3877       /* If the placeholder appears in the decl-specifier-seq of a function
3878 	 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3879 	 is a pack expansion, the invented template parameter is a template
3880 	 parameter pack.  */
3881       if (ppd->type_pack_expansion_p && is_auto (t))
3882 	TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3883       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3884         parameter_pack_p = true;
3885       break;
3886 
3887     case FIELD_DECL:
3888     case PARM_DECL:
3889       if (DECL_PACK_P (t))
3890         {
3891           /* We don't want to walk into the type of a PARM_DECL,
3892              because we don't want to see the type parameter pack.  */
3893           *walk_subtrees = 0;
3894 	  parameter_pack_p = true;
3895         }
3896       break;
3897 
3898     case VAR_DECL:
3899       if (DECL_PACK_P (t))
3900         {
3901           /* We don't want to walk into the type of a variadic capture proxy,
3902              because we don't want to see the type parameter pack.  */
3903           *walk_subtrees = 0;
3904 	  parameter_pack_p = true;
3905         }
3906       else if (variable_template_specialization_p (t))
3907 	{
3908 	  cp_walk_tree (&DECL_TI_ARGS (t),
3909 			find_parameter_packs_r,
3910 			ppd, ppd->visited);
3911 	  *walk_subtrees = 0;
3912 	}
3913       break;
3914 
3915     case CALL_EXPR:
3916       if (builtin_pack_call_p (t))
3917 	parameter_pack_p = true;
3918       break;
3919 
3920     case BASES:
3921       parameter_pack_p = true;
3922       break;
3923     default:
3924       /* Not a parameter pack.  */
3925       break;
3926     }
3927 
3928   if (parameter_pack_p)
3929     {
3930       /* Add this parameter pack to the list.  */
3931       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3932     }
3933 
3934   if (TYPE_P (t))
3935     cp_walk_tree (&TYPE_CONTEXT (t),
3936 		  &find_parameter_packs_r, ppd, ppd->visited);
3937 
3938   /* This switch statement will return immediately if we don't find a
3939      parameter pack.  ??? Should some of these be in cp_walk_subtrees?  */
3940   switch (TREE_CODE (t))
3941     {
3942     case BOUND_TEMPLATE_TEMPLATE_PARM:
3943       /* Check the template itself.  */
3944       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3945 		    &find_parameter_packs_r, ppd, ppd->visited);
3946       return NULL_TREE;
3947 
3948     case DECL_EXPR:
3949       {
3950 	tree decl = DECL_EXPR_DECL (t);
3951 	/* Ignore the declaration of a capture proxy for a parameter pack.  */
3952 	if (is_capture_proxy (decl))
3953 	  *walk_subtrees = 0;
3954 	if (is_typedef_decl (decl))
3955 	  /* Since we stop at typedefs above, we need to look through them at
3956 	     the point of the DECL_EXPR.  */
3957 	  cp_walk_tree (&DECL_ORIGINAL_TYPE (decl),
3958 			&find_parameter_packs_r, ppd, ppd->visited);
3959 	return NULL_TREE;
3960       }
3961 
3962     case TEMPLATE_DECL:
3963       if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
3964 	return NULL_TREE;
3965       cp_walk_tree (&TREE_TYPE (t),
3966 		    &find_parameter_packs_r, ppd, ppd->visited);
3967       return NULL_TREE;
3968 
3969     case TYPENAME_TYPE:
3970       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3971                    ppd, ppd->visited);
3972       *walk_subtrees = 0;
3973       return NULL_TREE;
3974 
3975     case TYPE_PACK_EXPANSION:
3976     case EXPR_PACK_EXPANSION:
3977       *walk_subtrees = 0;
3978       return NULL_TREE;
3979 
3980     case INTEGER_TYPE:
3981       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3982 		    ppd, ppd->visited);
3983       *walk_subtrees = 0;
3984       return NULL_TREE;
3985 
3986     case IDENTIFIER_NODE:
3987       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3988 		    ppd->visited);
3989       *walk_subtrees = 0;
3990       return NULL_TREE;
3991 
3992     case LAMBDA_EXPR:
3993       {
3994 	/* Look at explicit captures.  */
3995 	for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t);
3996 	     cap; cap = TREE_CHAIN (cap))
3997 	  cp_walk_tree (&TREE_VALUE (cap), &find_parameter_packs_r, ppd,
3998 			ppd->visited);
3999 	/* Since we defer implicit capture, look in the parms and body.  */
4000 	tree fn = lambda_function (t);
4001 	cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
4002 		      ppd->visited);
4003 	cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
4004 		      ppd->visited);
4005 	*walk_subtrees = 0;
4006 	return NULL_TREE;
4007       }
4008 
4009     case DECLTYPE_TYPE:
4010       {
4011 	/* When traversing a DECLTYPE_TYPE_EXPR, we need to set
4012 	   type_pack_expansion_p to false so that any placeholders
4013 	   within the expression don't get marked as parameter packs.  */
4014 	bool type_pack_expansion_p = ppd->type_pack_expansion_p;
4015 	ppd->type_pack_expansion_p = false;
4016 	cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
4017 		      ppd, ppd->visited);
4018 	ppd->type_pack_expansion_p = type_pack_expansion_p;
4019 	*walk_subtrees = 0;
4020 	return NULL_TREE;
4021       }
4022 
4023     case IF_STMT:
4024       cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
4025 		    ppd, ppd->visited);
4026       cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
4027 		    ppd, ppd->visited);
4028       cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
4029 		    ppd, ppd->visited);
4030       /* Don't walk into IF_STMT_EXTRA_ARGS.  */
4031       *walk_subtrees = 0;
4032       return NULL_TREE;
4033 
4034     default:
4035       return NULL_TREE;
4036     }
4037 
4038   return NULL_TREE;
4039 }
4040 
4041 /* Determines if the expression or type T uses any parameter packs.  */
4042 tree
uses_parameter_packs(tree t)4043 uses_parameter_packs (tree t)
4044 {
4045   tree parameter_packs = NULL_TREE;
4046   struct find_parameter_pack_data ppd;
4047   ppd.parameter_packs = &parameter_packs;
4048   ppd.visited = new hash_set<tree>;
4049   ppd.type_pack_expansion_p = false;
4050   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4051   delete ppd.visited;
4052   return parameter_packs;
4053 }
4054 
4055 /* Turn ARG, which may be an expression, type, or a TREE_LIST
4056    representation a base-class initializer into a parameter pack
4057    expansion. If all goes well, the resulting node will be an
4058    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
4059    respectively.  */
4060 tree
make_pack_expansion(tree arg,tsubst_flags_t complain)4061 make_pack_expansion (tree arg, tsubst_flags_t complain)
4062 {
4063   tree result;
4064   tree parameter_packs = NULL_TREE;
4065   bool for_types = false;
4066   struct find_parameter_pack_data ppd;
4067 
4068   if (!arg || arg == error_mark_node)
4069     return arg;
4070 
4071   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
4072     {
4073       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
4074          class initializer.  In this case, the TREE_PURPOSE will be a
4075          _TYPE node (representing the base class expansion we're
4076          initializing) and the TREE_VALUE will be a TREE_LIST
4077          containing the initialization arguments.
4078 
4079          The resulting expansion looks somewhat different from most
4080          expansions. Rather than returning just one _EXPANSION, we
4081          return a TREE_LIST whose TREE_PURPOSE is a
4082          TYPE_PACK_EXPANSION containing the bases that will be
4083          initialized.  The TREE_VALUE will be identical to the
4084          original TREE_VALUE, which is a list of arguments that will
4085          be passed to each base.  We do not introduce any new pack
4086          expansion nodes into the TREE_VALUE (although it is possible
4087          that some already exist), because the TREE_PURPOSE and
4088          TREE_VALUE all need to be expanded together with the same
4089          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
4090          resulting TREE_PURPOSE will mention the parameter packs in
4091          both the bases and the arguments to the bases.  */
4092       tree purpose;
4093       tree value;
4094       tree parameter_packs = NULL_TREE;
4095 
4096       /* Determine which parameter packs will be used by the base
4097          class expansion.  */
4098       ppd.visited = new hash_set<tree>;
4099       ppd.parameter_packs = &parameter_packs;
4100       ppd.type_pack_expansion_p = false;
4101       gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
4102       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
4103                     &ppd, ppd.visited);
4104 
4105       if (parameter_packs == NULL_TREE)
4106         {
4107 	  if (complain & tf_error)
4108 	    error ("base initializer expansion %qT contains no parameter packs",
4109 		   arg);
4110           delete ppd.visited;
4111           return error_mark_node;
4112         }
4113 
4114       if (TREE_VALUE (arg) != void_type_node)
4115         {
4116           /* Collect the sets of parameter packs used in each of the
4117              initialization arguments.  */
4118           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
4119             {
4120               /* Determine which parameter packs will be expanded in this
4121                  argument.  */
4122               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
4123                             &ppd, ppd.visited);
4124             }
4125         }
4126 
4127       delete ppd.visited;
4128 
4129       /* Create the pack expansion type for the base type.  */
4130       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
4131       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
4132       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
4133       PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
4134 
4135       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4136 	 they will rarely be compared to anything.  */
4137       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
4138 
4139       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
4140     }
4141 
4142   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
4143     for_types = true;
4144 
4145   /* Build the PACK_EXPANSION_* node.  */
4146   result = for_types
4147      ? cxx_make_type (TYPE_PACK_EXPANSION)
4148      : make_node (EXPR_PACK_EXPANSION);
4149   SET_PACK_EXPANSION_PATTERN (result, arg);
4150   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
4151     {
4152       /* Propagate type and const-expression information.  */
4153       TREE_TYPE (result) = TREE_TYPE (arg);
4154       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4155       /* Mark this read now, since the expansion might be length 0.  */
4156       mark_exp_read (arg);
4157     }
4158   else
4159     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4160        they will rarely be compared to anything.  */
4161     SET_TYPE_STRUCTURAL_EQUALITY (result);
4162 
4163   /* Determine which parameter packs will be expanded.  */
4164   ppd.parameter_packs = &parameter_packs;
4165   ppd.visited = new hash_set<tree>;
4166   ppd.type_pack_expansion_p = TYPE_P (arg);
4167   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4168   delete ppd.visited;
4169 
4170   /* Make sure we found some parameter packs.  */
4171   if (parameter_packs == NULL_TREE)
4172     {
4173       if (complain & tf_error)
4174 	{
4175 	  if (TYPE_P (arg))
4176 	    error ("expansion pattern %qT contains no parameter packs", arg);
4177 	  else
4178 	    error ("expansion pattern %qE contains no parameter packs", arg);
4179 	}
4180       return error_mark_node;
4181     }
4182   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4183 
4184   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4185 
4186   return result;
4187 }
4188 
4189 /* Checks T for any "bare" parameter packs, which have not yet been
4190    expanded, and issues an error if any are found. This operation can
4191    only be done on full expressions or types (e.g., an expression
4192    statement, "if" condition, etc.), because we could have expressions like:
4193 
4194      foo(f(g(h(args)))...)
4195 
4196    where "args" is a parameter pack. check_for_bare_parameter_packs
4197    should not be called for the subexpressions args, h(args),
4198    g(h(args)), or f(g(h(args))), because we would produce erroneous
4199    error messages.
4200 
4201    Returns TRUE and emits an error if there were bare parameter packs,
4202    returns FALSE otherwise.  */
4203 bool
check_for_bare_parameter_packs(tree t,location_t loc)4204 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4205 {
4206   tree parameter_packs = NULL_TREE;
4207   struct find_parameter_pack_data ppd;
4208 
4209   if (!processing_template_decl || !t || t == error_mark_node)
4210     return false;
4211 
4212   /* A lambda might use a parameter pack from the containing context.  */
4213   if (current_class_type && LAMBDA_TYPE_P (current_class_type)
4214       && CLASSTYPE_TEMPLATE_INFO (current_class_type))
4215     return false;
4216 
4217   if (TREE_CODE (t) == TYPE_DECL)
4218     t = TREE_TYPE (t);
4219 
4220   ppd.parameter_packs = &parameter_packs;
4221   ppd.visited = new hash_set<tree>;
4222   ppd.type_pack_expansion_p = false;
4223   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4224   delete ppd.visited;
4225 
4226   if (parameter_packs)
4227     {
4228       if (loc == UNKNOWN_LOCATION)
4229 	loc = cp_expr_loc_or_input_loc (t);
4230       error_at (loc, "parameter packs not expanded with %<...%>:");
4231       while (parameter_packs)
4232         {
4233           tree pack = TREE_VALUE (parameter_packs);
4234           tree name = NULL_TREE;
4235 
4236           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4237               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4238             name = TYPE_NAME (pack);
4239           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4240             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4241 	  else if (TREE_CODE (pack) == CALL_EXPR)
4242 	    name = DECL_NAME (CALL_EXPR_FN (pack));
4243           else
4244             name = DECL_NAME (pack);
4245 
4246 	  if (name)
4247 	    inform (loc, "        %qD", name);
4248 	  else
4249 	    inform (loc, "        %s", "<anonymous>");
4250 
4251           parameter_packs = TREE_CHAIN (parameter_packs);
4252         }
4253 
4254       return true;
4255     }
4256 
4257   return false;
4258 }
4259 
4260 /* Expand any parameter packs that occur in the template arguments in
4261    ARGS.  */
4262 tree
expand_template_argument_pack(tree args)4263 expand_template_argument_pack (tree args)
4264 {
4265   if (args == error_mark_node)
4266     return error_mark_node;
4267 
4268   tree result_args = NULL_TREE;
4269   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4270   int num_result_args = -1;
4271   int non_default_args_count = -1;
4272 
4273   /* First, determine if we need to expand anything, and the number of
4274      slots we'll need.  */
4275   for (in_arg = 0; in_arg < nargs; ++in_arg)
4276     {
4277       tree arg = TREE_VEC_ELT (args, in_arg);
4278       if (arg == NULL_TREE)
4279 	return args;
4280       if (ARGUMENT_PACK_P (arg))
4281         {
4282           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4283           if (num_result_args < 0)
4284             num_result_args = in_arg + num_packed;
4285           else
4286             num_result_args += num_packed;
4287         }
4288       else
4289         {
4290           if (num_result_args >= 0)
4291             num_result_args++;
4292         }
4293     }
4294 
4295   /* If no expansion is necessary, we're done.  */
4296   if (num_result_args < 0)
4297     return args;
4298 
4299   /* Expand arguments.  */
4300   result_args = make_tree_vec (num_result_args);
4301   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4302     non_default_args_count =
4303       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4304   for (in_arg = 0; in_arg < nargs; ++in_arg)
4305     {
4306       tree arg = TREE_VEC_ELT (args, in_arg);
4307       if (ARGUMENT_PACK_P (arg))
4308         {
4309           tree packed = ARGUMENT_PACK_ARGS (arg);
4310           int i, num_packed = TREE_VEC_LENGTH (packed);
4311           for (i = 0; i < num_packed; ++i, ++out_arg)
4312             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4313 	  if (non_default_args_count > 0)
4314 	    non_default_args_count += num_packed - 1;
4315         }
4316       else
4317         {
4318           TREE_VEC_ELT (result_args, out_arg) = arg;
4319           ++out_arg;
4320         }
4321     }
4322   if (non_default_args_count >= 0)
4323     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4324   return result_args;
4325 }
4326 
4327 /* Checks if DECL shadows a template parameter.
4328 
4329    [temp.local]: A template-parameter shall not be redeclared within its
4330    scope (including nested scopes).
4331 
4332    Emits an error and returns TRUE if the DECL shadows a parameter,
4333    returns FALSE otherwise.  */
4334 
4335 bool
check_template_shadow(tree decl)4336 check_template_shadow (tree decl)
4337 {
4338   tree olddecl;
4339 
4340   /* If we're not in a template, we can't possibly shadow a template
4341      parameter.  */
4342   if (!current_template_parms)
4343     return true;
4344 
4345   /* Figure out what we're shadowing.  */
4346   decl = OVL_FIRST (decl);
4347   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4348 
4349   /* If there's no previous binding for this name, we're not shadowing
4350      anything, let alone a template parameter.  */
4351   if (!olddecl)
4352     return true;
4353 
4354   /* If we're not shadowing a template parameter, we're done.  Note
4355      that OLDDECL might be an OVERLOAD (or perhaps even an
4356      ERROR_MARK), so we can't just blithely assume it to be a _DECL
4357      node.  */
4358   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4359     return true;
4360 
4361   /* We check for decl != olddecl to avoid bogus errors for using a
4362      name inside a class.  We check TPFI to avoid duplicate errors for
4363      inline member templates.  */
4364   if (decl == olddecl
4365       || (DECL_TEMPLATE_PARM_P (decl)
4366 	  && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4367     return true;
4368 
4369   /* Don't complain about the injected class name, as we've already
4370      complained about the class itself.  */
4371   if (DECL_SELF_REFERENCE_P (decl))
4372     return false;
4373 
4374   if (DECL_TEMPLATE_PARM_P (decl))
4375     error ("declaration of template parameter %q+D shadows "
4376 	   "template parameter", decl);
4377   else
4378     error ("declaration of %q+#D shadows template parameter", decl);
4379   inform (DECL_SOURCE_LOCATION (olddecl),
4380 	  "template parameter %qD declared here", olddecl);
4381   return false;
4382 }
4383 
4384 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4385    ORIG_LEVEL, DECL, and TYPE.  */
4386 
4387 static tree
build_template_parm_index(int index,int level,int orig_level,tree decl,tree type)4388 build_template_parm_index (int index,
4389 			   int level,
4390 			   int orig_level,
4391 			   tree decl,
4392 			   tree type)
4393 {
4394   tree t = make_node (TEMPLATE_PARM_INDEX);
4395   TEMPLATE_PARM_IDX (t) = index;
4396   TEMPLATE_PARM_LEVEL (t) = level;
4397   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4398   TEMPLATE_PARM_DECL (t) = decl;
4399   TREE_TYPE (t) = type;
4400   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4401   TREE_READONLY (t) = TREE_READONLY (decl);
4402 
4403   return t;
4404 }
4405 
4406 /* Find the canonical type parameter for the given template type
4407    parameter.  Returns the canonical type parameter, which may be TYPE
4408    if no such parameter existed.  */
4409 
4410 static tree
canonical_type_parameter(tree type)4411 canonical_type_parameter (tree type)
4412 {
4413   tree list;
4414   int idx = TEMPLATE_TYPE_IDX (type);
4415 
4416   gcc_assert (TREE_CODE (type) != TEMPLATE_TEMPLATE_PARM);
4417 
4418   if (!canonical_template_parms)
4419     vec_alloc (canonical_template_parms, idx + 1);
4420 
4421   if (canonical_template_parms->length () <= (unsigned) idx)
4422     vec_safe_grow_cleared (canonical_template_parms, idx + 1);
4423 
4424   list = (*canonical_template_parms)[idx];
4425   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4426     list = TREE_CHAIN (list);
4427 
4428   if (list)
4429     return TREE_VALUE (list);
4430   else
4431     {
4432       (*canonical_template_parms)[idx]
4433 	= tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4434       return type;
4435     }
4436 }
4437 
4438 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4439    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
4440    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4441    new one is created.  */
4442 
4443 static tree
reduce_template_parm_level(tree index,tree type,int levels,tree args,tsubst_flags_t complain)4444 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4445 			    tsubst_flags_t complain)
4446 {
4447   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4448       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4449 	  != TEMPLATE_PARM_LEVEL (index) - levels)
4450       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4451     {
4452       tree orig_decl = TEMPLATE_PARM_DECL (index);
4453 
4454       tree decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4455 			      TREE_CODE (orig_decl), DECL_NAME (orig_decl),
4456 			      type);
4457       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4458       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4459       DECL_VIRTUAL_P (decl) = DECL_VIRTUAL_P (orig_decl);
4460       DECL_ARTIFICIAL (decl) = 1;
4461       SET_DECL_TEMPLATE_PARM_P (decl);
4462 
4463       tree tpi = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4464 					    TEMPLATE_PARM_LEVEL (index) - levels,
4465 					    TEMPLATE_PARM_ORIG_LEVEL (index),
4466 					    decl, type);
4467       TEMPLATE_PARM_DESCENDANTS (index) = tpi;
4468       TEMPLATE_PARM_PARAMETER_PACK (tpi)
4469 	= TEMPLATE_PARM_PARAMETER_PACK (index);
4470 
4471 	/* Template template parameters need this.  */
4472       tree inner = decl;
4473       if (TREE_CODE (decl) == TEMPLATE_DECL)
4474 	{
4475 	  inner = build_decl (DECL_SOURCE_LOCATION (decl),
4476 			      TYPE_DECL, DECL_NAME (decl), type);
4477 	  DECL_TEMPLATE_RESULT (decl) = inner;
4478 	  DECL_ARTIFICIAL (inner) = true;
4479 	  DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4480 	    (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4481 	}
4482 
4483       /* Attach the TPI to the decl.  */
4484       if (TREE_CODE (inner) == TYPE_DECL)
4485 	TEMPLATE_TYPE_PARM_INDEX (type) = tpi;
4486       else
4487 	DECL_INITIAL (decl) = tpi;
4488     }
4489 
4490   return TEMPLATE_PARM_DESCENDANTS (index);
4491 }
4492 
4493 /* Process information from new template parameter PARM and append it
4494    to the LIST being built.  This new parameter is a non-type
4495    parameter iff IS_NON_TYPE is true. This new parameter is a
4496    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4497    is in PARM_LOC.  */
4498 
4499 tree
process_template_parm(tree list,location_t parm_loc,tree parm,bool is_non_type,bool is_parameter_pack)4500 process_template_parm (tree list, location_t parm_loc, tree parm,
4501 		       bool is_non_type, bool is_parameter_pack)
4502 {
4503   tree decl = 0;
4504   int idx = 0;
4505 
4506   gcc_assert (TREE_CODE (parm) == TREE_LIST);
4507   tree defval = TREE_PURPOSE (parm);
4508   tree constr = TREE_TYPE (parm);
4509 
4510   if (list)
4511     {
4512       tree p = tree_last (list);
4513 
4514       if (p && TREE_VALUE (p) != error_mark_node)
4515         {
4516           p = TREE_VALUE (p);
4517           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4518             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4519           else
4520             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4521         }
4522 
4523       ++idx;
4524     }
4525 
4526   if (is_non_type)
4527     {
4528       parm = TREE_VALUE (parm);
4529 
4530       SET_DECL_TEMPLATE_PARM_P (parm);
4531 
4532       if (TREE_TYPE (parm) != error_mark_node)
4533 	{
4534 	  /* [temp.param]
4535 
4536 	     The top-level cv-qualifiers on the template-parameter are
4537 	     ignored when determining its type.  */
4538 	  TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4539 	  if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4540 	    TREE_TYPE (parm) = error_mark_node;
4541 	  else if (uses_parameter_packs (TREE_TYPE (parm))
4542 		   && !is_parameter_pack
4543 		   /* If we're in a nested template parameter list, the template
4544 		      template parameter could be a parameter pack.  */
4545 		   && processing_template_parmlist == 1)
4546 	    {
4547 	      /* This template parameter is not a parameter pack, but it
4548 		 should be. Complain about "bare" parameter packs.  */
4549 	      check_for_bare_parameter_packs (TREE_TYPE (parm));
4550 
4551 	      /* Recover by calling this a parameter pack.  */
4552 	      is_parameter_pack = true;
4553 	    }
4554 	}
4555 
4556       /* A template parameter is not modifiable.  */
4557       TREE_CONSTANT (parm) = 1;
4558       TREE_READONLY (parm) = 1;
4559       decl = build_decl (parm_loc,
4560 			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4561       TREE_CONSTANT (decl) = 1;
4562       TREE_READONLY (decl) = 1;
4563       DECL_INITIAL (parm) = DECL_INITIAL (decl)
4564 	= build_template_parm_index (idx, processing_template_decl,
4565 				     processing_template_decl,
4566 				     decl, TREE_TYPE (parm));
4567 
4568       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4569 	= is_parameter_pack;
4570     }
4571   else
4572     {
4573       tree t;
4574       parm = TREE_VALUE (TREE_VALUE (parm));
4575 
4576       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4577 	{
4578 	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4579 	  /* This is for distinguishing between real templates and template
4580 	     template parameters */
4581 	  TREE_TYPE (parm) = t;
4582 
4583 	  /* any_template_parm_r expects to be able to get the targs of a
4584 	     DECL_TEMPLATE_RESULT.  */
4585 	  tree result = DECL_TEMPLATE_RESULT (parm);
4586 	  TREE_TYPE (result) = t;
4587 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (parm));
4588 	  tree tinfo = build_template_info (parm, args);
4589 	  retrofit_lang_decl (result);
4590 	  DECL_TEMPLATE_INFO (result) = tinfo;
4591 
4592 	  decl = parm;
4593 	}
4594       else
4595 	{
4596 	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
4597 	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4598 	  decl = build_decl (parm_loc,
4599 			     TYPE_DECL, parm, t);
4600 	}
4601 
4602       TYPE_NAME (t) = decl;
4603       TYPE_STUB_DECL (t) = decl;
4604       parm = decl;
4605       TEMPLATE_TYPE_PARM_INDEX (t)
4606 	= build_template_parm_index (idx, processing_template_decl,
4607 				     processing_template_decl,
4608 				     decl, TREE_TYPE (parm));
4609       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4610       if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4611 	SET_TYPE_STRUCTURAL_EQUALITY (t);
4612       else
4613 	TYPE_CANONICAL (t) = canonical_type_parameter (t);
4614     }
4615   DECL_ARTIFICIAL (decl) = 1;
4616   SET_DECL_TEMPLATE_PARM_P (decl);
4617 
4618   /* Build requirements for the type/template parameter.
4619      This must be done after SET_DECL_TEMPLATE_PARM_P or
4620      process_template_parm could fail. */
4621   tree reqs = finish_shorthand_constraint (parm, constr);
4622 
4623   decl = pushdecl (decl);
4624   if (!is_non_type)
4625     parm = decl;
4626 
4627   /* Build the parameter node linking the parameter declaration,
4628      its default argument (if any), and its constraints (if any). */
4629   parm = build_tree_list (defval, parm);
4630   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4631 
4632   return chainon (list, parm);
4633 }
4634 
4635 /* The end of a template parameter list has been reached.  Process the
4636    tree list into a parameter vector, converting each parameter into a more
4637    useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
4638    as PARM_DECLs.  */
4639 
4640 tree
end_template_parm_list(tree parms)4641 end_template_parm_list (tree parms)
4642 {
4643   int nparms;
4644   tree parm, next;
4645   tree saved_parmlist = make_tree_vec (list_length (parms));
4646 
4647   /* Pop the dummy parameter level and add the real one.  */
4648   current_template_parms = TREE_CHAIN (current_template_parms);
4649 
4650   current_template_parms
4651     = tree_cons (size_int (processing_template_decl),
4652 		 saved_parmlist, current_template_parms);
4653 
4654   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
4655     {
4656       next = TREE_CHAIN (parm);
4657       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
4658       TREE_CHAIN (parm) = NULL_TREE;
4659     }
4660 
4661   --processing_template_parmlist;
4662 
4663   return saved_parmlist;
4664 }
4665 
4666 // Explicitly indicate the end of the template parameter list. We assume
4667 // that the current template parameters have been constructed and/or
4668 // managed explicitly, as when creating new template template parameters
4669 // from a shorthand constraint.
4670 void
end_template_parm_list()4671 end_template_parm_list ()
4672 {
4673   --processing_template_parmlist;
4674 }
4675 
4676 /* end_template_decl is called after a template declaration is seen.  */
4677 
4678 void
end_template_decl(void)4679 end_template_decl (void)
4680 {
4681   reset_specialization ();
4682 
4683   if (! processing_template_decl)
4684     return;
4685 
4686   /* This matches the pushlevel in begin_template_parm_list.  */
4687   finish_scope ();
4688 
4689   --processing_template_decl;
4690   current_template_parms = TREE_CHAIN (current_template_parms);
4691 }
4692 
4693 /* Takes a TEMPLATE_PARM_P or DECL_TEMPLATE_PARM_P node or a TREE_LIST
4694    thereof, and converts it into an argument suitable to be passed to
4695    the type substitution functions.  Note that if the TREE_LIST contains
4696    an error_mark node, the returned argument is error_mark_node.  */
4697 
4698 tree
template_parm_to_arg(tree t)4699 template_parm_to_arg (tree t)
4700 {
4701   if (!t)
4702     return NULL_TREE;
4703 
4704   if (TREE_CODE (t) == TREE_LIST)
4705     t = TREE_VALUE (t);
4706 
4707   if (error_operand_p (t))
4708     return error_mark_node;
4709 
4710   if (DECL_P (t) && DECL_TEMPLATE_PARM_P (t))
4711     {
4712       if (TREE_CODE (t) == TYPE_DECL
4713 	  || TREE_CODE (t) == TEMPLATE_DECL)
4714 	t = TREE_TYPE (t);
4715       else
4716 	t = DECL_INITIAL (t);
4717     }
4718 
4719   gcc_assert (TEMPLATE_PARM_P (t));
4720 
4721   if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
4722       || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
4723     {
4724       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4725 	{
4726 	  /* Turn this argument into a TYPE_ARGUMENT_PACK
4727 	     with a single element, which expands T.  */
4728 	  tree vec = make_tree_vec (1);
4729 	  if (CHECKING_P)
4730 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4731 
4732 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4733 
4734 	  t = cxx_make_type (TYPE_ARGUMENT_PACK);
4735 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4736 	}
4737     }
4738   else
4739     {
4740       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4741 	{
4742 	  /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4743 	     with a single element, which expands T.  */
4744 	  tree vec = make_tree_vec (1);
4745 	  if (CHECKING_P)
4746 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4747 
4748 	  t = convert_from_reference (t);
4749 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4750 
4751 	  t  = make_node (NONTYPE_ARGUMENT_PACK);
4752 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4753 	}
4754       else
4755 	t = convert_from_reference (t);
4756     }
4757   return t;
4758 }
4759 
4760 /* Given a single level of template parameters (a TREE_VEC), return it
4761    as a set of template arguments.  */
4762 
4763 tree
template_parms_level_to_args(tree parms)4764 template_parms_level_to_args (tree parms)
4765 {
4766   tree a = copy_node (parms);
4767   TREE_TYPE (a) = NULL_TREE;
4768   for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4769     TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4770 
4771   if (CHECKING_P)
4772     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4773 
4774   return a;
4775 }
4776 
4777 /* Given a set of template parameters, return them as a set of template
4778    arguments.  The template parameters are represented as a TREE_VEC, in
4779    the form documented in cp-tree.h for template arguments.  */
4780 
4781 tree
template_parms_to_args(tree parms)4782 template_parms_to_args (tree parms)
4783 {
4784   tree header;
4785   tree args = NULL_TREE;
4786   int length = TMPL_PARMS_DEPTH (parms);
4787   int l = length;
4788 
4789   /* If there is only one level of template parameters, we do not
4790      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4791      TREE_VEC containing the arguments.  */
4792   if (length > 1)
4793     args = make_tree_vec (length);
4794 
4795   for (header = parms; header; header = TREE_CHAIN (header))
4796     {
4797       tree a = template_parms_level_to_args (TREE_VALUE (header));
4798 
4799       if (length > 1)
4800 	TREE_VEC_ELT (args, --l) = a;
4801       else
4802 	args = a;
4803     }
4804 
4805   return args;
4806 }
4807 
4808 /* Within the declaration of a template, return the currently active
4809    template parameters as an argument TREE_VEC.  */
4810 
4811 static tree
current_template_args(void)4812 current_template_args (void)
4813 {
4814   return template_parms_to_args (current_template_parms);
4815 }
4816 
4817 /* Return the fully generic arguments for of TMPL, i.e. what
4818    current_template_args would be while parsing it.  */
4819 
4820 tree
generic_targs_for(tree tmpl)4821 generic_targs_for (tree tmpl)
4822 {
4823   if (tmpl == NULL_TREE)
4824     return NULL_TREE;
4825   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
4826       || DECL_TEMPLATE_SPECIALIZATION (tmpl))
4827     /* DECL_TEMPLATE_RESULT doesn't have the arguments we want.  For a template
4828        template parameter, it has no TEMPLATE_INFO; for a partial
4829        specialization, it has the arguments for the primary template, and we
4830        want the arguments for the partial specialization.  */;
4831   else if (tree result = DECL_TEMPLATE_RESULT (tmpl))
4832     if (tree ti = get_template_info (result))
4833       return TI_ARGS (ti);
4834   return template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl));
4835 }
4836 
4837 /* Update the declared TYPE by doing any lookups which were thought to be
4838    dependent, but are not now that we know the SCOPE of the declarator.  */
4839 
4840 tree
maybe_update_decl_type(tree orig_type,tree scope)4841 maybe_update_decl_type (tree orig_type, tree scope)
4842 {
4843   tree type = orig_type;
4844 
4845   if (type == NULL_TREE)
4846     return type;
4847 
4848   if (TREE_CODE (orig_type) == TYPE_DECL)
4849     type = TREE_TYPE (type);
4850 
4851   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4852       && dependent_type_p (type)
4853       /* Don't bother building up the args in this case.  */
4854       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4855     {
4856       /* tsubst in the args corresponding to the template parameters,
4857 	 including auto if present.  Most things will be unchanged, but
4858 	 make_typename_type and tsubst_qualified_id will resolve
4859 	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4860       tree args = current_template_args ();
4861       tree auto_node = type_uses_auto (type);
4862       tree pushed;
4863       if (auto_node)
4864 	{
4865 	  tree auto_vec = make_tree_vec (1);
4866 	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
4867 	  args = add_to_template_args (args, auto_vec);
4868 	}
4869       pushed = push_scope (scope);
4870       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4871       if (pushed)
4872 	pop_scope (scope);
4873     }
4874 
4875   if (type == error_mark_node)
4876     return orig_type;
4877 
4878   if (TREE_CODE (orig_type) == TYPE_DECL)
4879     {
4880       if (same_type_p (type, TREE_TYPE (orig_type)))
4881 	type = orig_type;
4882       else
4883 	type = TYPE_NAME (type);
4884     }
4885   return type;
4886 }
4887 
4888 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4889    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
4890    the new  template is a member template. */
4891 
4892 static tree
build_template_decl(tree decl,tree parms,bool member_template_p)4893 build_template_decl (tree decl, tree parms, bool member_template_p)
4894 {
4895   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4896   SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
4897   DECL_TEMPLATE_PARMS (tmpl) = parms;
4898   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4899   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4900   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4901 
4902   return tmpl;
4903 }
4904 
4905 struct template_parm_data
4906 {
4907   /* The level of the template parameters we are currently
4908      processing.  */
4909   int level;
4910 
4911   /* The index of the specialization argument we are currently
4912      processing.  */
4913   int current_arg;
4914 
4915   /* An array whose size is the number of template parameters.  The
4916      elements are nonzero if the parameter has been used in any one
4917      of the arguments processed so far.  */
4918   int* parms;
4919 
4920   /* An array whose size is the number of template arguments.  The
4921      elements are nonzero if the argument makes use of template
4922      parameters of this level.  */
4923   int* arg_uses_template_parms;
4924 };
4925 
4926 /* Subroutine of push_template_decl used to see if each template
4927    parameter in a partial specialization is used in the explicit
4928    argument list.  If T is of the LEVEL given in DATA (which is
4929    treated as a template_parm_data*), then DATA->PARMS is marked
4930    appropriately.  */
4931 
4932 static int
mark_template_parm(tree t,void * data)4933 mark_template_parm (tree t, void* data)
4934 {
4935   int level;
4936   int idx;
4937   struct template_parm_data* tpd = (struct template_parm_data*) data;
4938 
4939   template_parm_level_and_index (t, &level, &idx);
4940 
4941   if (level == tpd->level)
4942     {
4943       tpd->parms[idx] = 1;
4944       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4945     }
4946 
4947   /* In C++17 the type of a non-type argument is a deduced context.  */
4948   if (cxx_dialect >= cxx17
4949       && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4950     for_each_template_parm (TREE_TYPE (t),
4951 			    &mark_template_parm,
4952 			    data,
4953 			    NULL,
4954 			    /*include_nondeduced_p=*/false);
4955 
4956   /* Return zero so that for_each_template_parm will continue the
4957      traversal of the tree; we want to mark *every* template parm.  */
4958   return 0;
4959 }
4960 
4961 /* Process the partial specialization DECL.  */
4962 
4963 static tree
process_partial_specialization(tree decl)4964 process_partial_specialization (tree decl)
4965 {
4966   tree type = TREE_TYPE (decl);
4967   tree tinfo = get_template_info (decl);
4968   tree maintmpl = TI_TEMPLATE (tinfo);
4969   tree specargs = TI_ARGS (tinfo);
4970   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4971   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4972   tree inner_parms;
4973   tree inst;
4974   int nargs = TREE_VEC_LENGTH (inner_args);
4975   int ntparms;
4976   int  i;
4977   bool did_error_intro = false;
4978   struct template_parm_data tpd;
4979   struct template_parm_data tpd2;
4980 
4981   gcc_assert (current_template_parms);
4982 
4983   /* A concept cannot be specialized.  */
4984   if (flag_concepts && variable_concept_p (maintmpl))
4985     {
4986       error ("specialization of variable concept %q#D", maintmpl);
4987       return error_mark_node;
4988     }
4989 
4990   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4991   ntparms = TREE_VEC_LENGTH (inner_parms);
4992 
4993   /* We check that each of the template parameters given in the
4994      partial specialization is used in the argument list to the
4995      specialization.  For example:
4996 
4997        template <class T> struct S;
4998        template <class T> struct S<T*>;
4999 
5000      The second declaration is OK because `T*' uses the template
5001      parameter T, whereas
5002 
5003        template <class T> struct S<int>;
5004 
5005      is no good.  Even trickier is:
5006 
5007        template <class T>
5008        struct S1
5009        {
5010 	  template <class U>
5011 	  struct S2;
5012 	  template <class U>
5013 	  struct S2<T>;
5014        };
5015 
5016      The S2<T> declaration is actually invalid; it is a
5017      full-specialization.  Of course,
5018 
5019 	  template <class U>
5020 	  struct S2<T (*)(U)>;
5021 
5022      or some such would have been OK.  */
5023   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
5024   tpd.parms = XALLOCAVEC (int, ntparms);
5025   memset (tpd.parms, 0, sizeof (int) * ntparms);
5026 
5027   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5028   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
5029   for (i = 0; i < nargs; ++i)
5030     {
5031       tpd.current_arg = i;
5032       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
5033 			      &mark_template_parm,
5034 			      &tpd,
5035 			      NULL,
5036 			      /*include_nondeduced_p=*/false);
5037     }
5038   for (i = 0; i < ntparms; ++i)
5039     if (tpd.parms[i] == 0)
5040       {
5041 	/* One of the template parms was not used in a deduced context in the
5042 	   specialization.  */
5043 	if (!did_error_intro)
5044 	  {
5045 	    error ("template parameters not deducible in "
5046 		   "partial specialization:");
5047 	    did_error_intro = true;
5048 	  }
5049 
5050 	inform (input_location, "        %qD",
5051 		TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
5052       }
5053 
5054   if (did_error_intro)
5055     return error_mark_node;
5056 
5057   /* [temp.class.spec]
5058 
5059      The argument list of the specialization shall not be identical to
5060      the implicit argument list of the primary template.  */
5061   tree main_args
5062     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
5063   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
5064       && (!flag_concepts
5065 	  || !strictly_subsumes (current_template_constraints (),
5066 				 main_args, maintmpl)))
5067     {
5068       if (!flag_concepts)
5069         error ("partial specialization %q+D does not specialize "
5070 	       "any template arguments; to define the primary template, "
5071 	       "remove the template argument list", decl);
5072       else
5073         error ("partial specialization %q+D does not specialize any "
5074 	       "template arguments and is not more constrained than "
5075 	       "the primary template; to define the primary template, "
5076 	       "remove the template argument list", decl);
5077       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5078     }
5079 
5080   /* A partial specialization that replaces multiple parameters of the
5081      primary template with a pack expansion is less specialized for those
5082      parameters.  */
5083   if (nargs < DECL_NTPARMS (maintmpl))
5084     {
5085       error ("partial specialization is not more specialized than the "
5086 	     "primary template because it replaces multiple parameters "
5087 	     "with a pack expansion");
5088       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5089       /* Avoid crash in process_partial_specialization.  */
5090       return decl;
5091     }
5092 
5093   else if (nargs > DECL_NTPARMS (maintmpl))
5094     {
5095       error ("too many arguments for partial specialization %qT", type);
5096       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
5097       /* Avoid crash below.  */
5098       return decl;
5099     }
5100 
5101   /* If we aren't in a dependent class, we can actually try deduction.  */
5102   else if (tpd.level == 1
5103 	   /* FIXME we should be able to handle a partial specialization of a
5104 	      partial instantiation, but currently we can't (c++/41727).  */
5105 	   && TMPL_ARGS_DEPTH (specargs) == 1
5106 	   && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
5107     {
5108       auto_diagnostic_group d;
5109       if (permerror (input_location, "partial specialization %qD is not "
5110 		     "more specialized than", decl))
5111 	inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
5112 		maintmpl);
5113     }
5114 
5115   /* [temp.class.spec]
5116 
5117      A partially specialized non-type argument expression shall not
5118      involve template parameters of the partial specialization except
5119      when the argument expression is a simple identifier.
5120 
5121      The type of a template parameter corresponding to a specialized
5122      non-type argument shall not be dependent on a parameter of the
5123      specialization.
5124 
5125      Also, we verify that pack expansions only occur at the
5126      end of the argument list.  */
5127   tpd2.parms = 0;
5128   for (i = 0; i < nargs; ++i)
5129     {
5130       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
5131       tree arg = TREE_VEC_ELT (inner_args, i);
5132       tree packed_args = NULL_TREE;
5133       int j, len = 1;
5134 
5135       if (ARGUMENT_PACK_P (arg))
5136         {
5137           /* Extract the arguments from the argument pack. We'll be
5138              iterating over these in the following loop.  */
5139           packed_args = ARGUMENT_PACK_ARGS (arg);
5140           len = TREE_VEC_LENGTH (packed_args);
5141         }
5142 
5143       for (j = 0; j < len; j++)
5144         {
5145           if (packed_args)
5146             /* Get the Jth argument in the parameter pack.  */
5147             arg = TREE_VEC_ELT (packed_args, j);
5148 
5149           if (PACK_EXPANSION_P (arg))
5150             {
5151               /* Pack expansions must come at the end of the
5152                  argument list.  */
5153               if ((packed_args && j < len - 1)
5154                   || (!packed_args && i < nargs - 1))
5155                 {
5156                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5157                     error ("parameter pack argument %qE must be at the "
5158 			   "end of the template argument list", arg);
5159                   else
5160                     error ("parameter pack argument %qT must be at the "
5161 			   "end of the template argument list", arg);
5162                 }
5163             }
5164 
5165           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5166             /* We only care about the pattern.  */
5167             arg = PACK_EXPANSION_PATTERN (arg);
5168 
5169           if (/* These first two lines are the `non-type' bit.  */
5170               !TYPE_P (arg)
5171               && TREE_CODE (arg) != TEMPLATE_DECL
5172               /* This next two lines are the `argument expression is not just a
5173                  simple identifier' condition and also the `specialized
5174                  non-type argument' bit.  */
5175               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
5176 	      && !((REFERENCE_REF_P (arg)
5177 		    || TREE_CODE (arg) == VIEW_CONVERT_EXPR)
5178 		   && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
5179             {
5180               if ((!packed_args && tpd.arg_uses_template_parms[i])
5181                   || (packed_args && uses_template_parms (arg)))
5182 		error_at (cp_expr_loc_or_input_loc (arg),
5183 			  "template argument %qE involves template "
5184 			  "parameter(s)", arg);
5185               else
5186                 {
5187                   /* Look at the corresponding template parameter,
5188                      marking which template parameters its type depends
5189                      upon.  */
5190                   tree type = TREE_TYPE (parm);
5191 
5192                   if (!tpd2.parms)
5193                     {
5194                       /* We haven't yet initialized TPD2.  Do so now.  */
5195                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
5196                       /* The number of parameters here is the number in the
5197                          main template, which, as checked in the assertion
5198                          above, is NARGS.  */
5199                       tpd2.parms = XALLOCAVEC (int, nargs);
5200                       tpd2.level =
5201                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
5202                     }
5203 
5204                   /* Mark the template parameters.  But this time, we're
5205                      looking for the template parameters of the main
5206                      template, not in the specialization.  */
5207                   tpd2.current_arg = i;
5208                   tpd2.arg_uses_template_parms[i] = 0;
5209                   memset (tpd2.parms, 0, sizeof (int) * nargs);
5210                   for_each_template_parm (type,
5211                                           &mark_template_parm,
5212                                           &tpd2,
5213                                           NULL,
5214 					  /*include_nondeduced_p=*/false);
5215 
5216                   if (tpd2.arg_uses_template_parms [i])
5217                     {
5218                       /* The type depended on some template parameters.
5219                          If they are fully specialized in the
5220                          specialization, that's OK.  */
5221                       int j;
5222                       int count = 0;
5223                       for (j = 0; j < nargs; ++j)
5224                         if (tpd2.parms[j] != 0
5225                             && tpd.arg_uses_template_parms [j])
5226                           ++count;
5227                       if (count != 0)
5228                         error_n (input_location, count,
5229                                  "type %qT of template argument %qE depends "
5230                                  "on a template parameter",
5231                                  "type %qT of template argument %qE depends "
5232                                  "on template parameters",
5233                                  type,
5234                                  arg);
5235                     }
5236                 }
5237             }
5238         }
5239     }
5240 
5241   /* We should only get here once.  */
5242   if (TREE_CODE (decl) == TYPE_DECL)
5243     gcc_assert (!COMPLETE_TYPE_P (type));
5244 
5245   // Build the template decl.
5246   tree tmpl = build_template_decl (decl, current_template_parms,
5247 				   DECL_MEMBER_TEMPLATE_P (maintmpl));
5248   TREE_TYPE (tmpl) = type;
5249   DECL_TEMPLATE_RESULT (tmpl) = decl;
5250   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5251   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5252   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5253 
5254   /* Give template template parms a DECL_CONTEXT of the template
5255      for which they are a parameter.  */
5256   for (i = 0; i < ntparms; ++i)
5257     {
5258       tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5259       if (TREE_CODE (parm) == TEMPLATE_DECL)
5260 	DECL_CONTEXT (parm) = tmpl;
5261     }
5262 
5263   if (VAR_P (decl))
5264     /* We didn't register this in check_explicit_specialization so we could
5265        wait until the constraints were set.  */
5266     decl = register_specialization (decl, maintmpl, specargs, false, 0);
5267   else
5268     associate_classtype_constraints (type);
5269 
5270   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5271     = tree_cons (specargs, tmpl,
5272                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5273   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5274 
5275   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5276        inst = TREE_CHAIN (inst))
5277     {
5278       tree instance = TREE_VALUE (inst);
5279       if (TYPE_P (instance)
5280 	  ? (COMPLETE_TYPE_P (instance)
5281 	     && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5282 	  : DECL_TEMPLATE_INSTANTIATION (instance))
5283 	{
5284 	  tree spec = most_specialized_partial_spec (instance, tf_none);
5285 	  tree inst_decl = (DECL_P (instance)
5286 			    ? instance : TYPE_NAME (instance));
5287 	  if (!spec)
5288 	    /* OK */;
5289 	  else if (spec == error_mark_node)
5290 	    permerror (input_location,
5291 		       "declaration of %qD ambiguates earlier template "
5292 		       "instantiation for %qD", decl, inst_decl);
5293 	  else if (TREE_VALUE (spec) == tmpl)
5294 	    permerror (input_location,
5295 		       "partial specialization of %qD after instantiation "
5296 		       "of %qD", decl, inst_decl);
5297 	}
5298     }
5299 
5300   return decl;
5301 }
5302 
5303 /* PARM is a template parameter of some form; return the corresponding
5304    TEMPLATE_PARM_INDEX.  */
5305 
5306 static tree
get_template_parm_index(tree parm)5307 get_template_parm_index (tree parm)
5308 {
5309   if (TREE_CODE (parm) == PARM_DECL
5310       || TREE_CODE (parm) == CONST_DECL)
5311     parm = DECL_INITIAL (parm);
5312   else if (TREE_CODE (parm) == TYPE_DECL
5313 	   || TREE_CODE (parm) == TEMPLATE_DECL)
5314     parm = TREE_TYPE (parm);
5315   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5316       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5317       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5318     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5319   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5320   return parm;
5321 }
5322 
5323 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
5324    parameter packs used by the template parameter PARM.  */
5325 
5326 static void
fixed_parameter_pack_p_1(tree parm,struct find_parameter_pack_data * ppd)5327 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5328 {
5329   /* A type parm can't refer to another parm.  */
5330   if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5331     return;
5332   else if (TREE_CODE (parm) == PARM_DECL)
5333     {
5334       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5335 		    ppd, ppd->visited);
5336       return;
5337     }
5338 
5339   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5340 
5341   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5342   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5343     {
5344       tree p = TREE_VALUE (TREE_VEC_ELT (vec, i));
5345       if (template_parameter_pack_p (p))
5346 	/* Any packs in the type are expanded by this parameter.  */;
5347       else
5348 	fixed_parameter_pack_p_1 (p, ppd);
5349     }
5350 }
5351 
5352 /* PARM is a template parameter pack.  Return any parameter packs used in
5353    its type or the type of any of its template parameters.  If there are
5354    any such packs, it will be instantiated into a fixed template parameter
5355    list by partial instantiation rather than be fully deduced.  */
5356 
5357 tree
fixed_parameter_pack_p(tree parm)5358 fixed_parameter_pack_p (tree parm)
5359 {
5360   /* This can only be true in a member template.  */
5361   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5362     return NULL_TREE;
5363   /* This can only be true for a parameter pack.  */
5364   if (!template_parameter_pack_p (parm))
5365     return NULL_TREE;
5366   /* A type parm can't refer to another parm.  */
5367   if (TREE_CODE (parm) == TYPE_DECL)
5368     return NULL_TREE;
5369 
5370   tree parameter_packs = NULL_TREE;
5371   struct find_parameter_pack_data ppd;
5372   ppd.parameter_packs = &parameter_packs;
5373   ppd.visited = new hash_set<tree>;
5374   ppd.type_pack_expansion_p = false;
5375 
5376   fixed_parameter_pack_p_1 (parm, &ppd);
5377 
5378   delete ppd.visited;
5379   return parameter_packs;
5380 }
5381 
5382 /* Check that a template declaration's use of default arguments and
5383    parameter packs is not invalid.  Here, PARMS are the template
5384    parameters.  IS_PRIMARY is true if DECL is the thing declared by
5385    a primary template.  IS_PARTIAL is true if DECL is a partial
5386    specialization.
5387 
5388    IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5389    function template declaration or a friend class template
5390    declaration.  In the function case, 1 indicates a declaration, 2
5391    indicates a redeclaration.  When IS_FRIEND_DECL=2, no errors are
5392    emitted for extraneous default arguments.
5393 
5394    Returns TRUE if there were no errors found, FALSE otherwise. */
5395 
5396 bool
check_default_tmpl_args(tree decl,tree parms,bool is_primary,bool is_partial,int is_friend_decl)5397 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5398                          bool is_partial, int is_friend_decl)
5399 {
5400   const char *msg;
5401   int last_level_to_check;
5402   tree parm_level;
5403   bool no_errors = true;
5404 
5405   /* [temp.param]
5406 
5407      A default template-argument shall not be specified in a
5408      function template declaration or a function template definition, nor
5409      in the template-parameter-list of the definition of a member of a
5410      class template.  */
5411 
5412   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5413       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
5414     /* You can't have a function template declaration in a local
5415        scope, nor you can you define a member of a class template in a
5416        local scope.  */
5417     return true;
5418 
5419   if ((TREE_CODE (decl) == TYPE_DECL
5420        && TREE_TYPE (decl)
5421        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5422       || (TREE_CODE (decl) == FUNCTION_DECL
5423 	  && LAMBDA_FUNCTION_P (decl)))
5424     /* A lambda doesn't have an explicit declaration; don't complain
5425        about the parms of the enclosing class.  */
5426     return true;
5427 
5428   if (current_class_type
5429       && !TYPE_BEING_DEFINED (current_class_type)
5430       && DECL_LANG_SPECIFIC (decl)
5431       && DECL_DECLARES_FUNCTION_P (decl)
5432       /* If this is either a friend defined in the scope of the class
5433 	 or a member function.  */
5434       && (DECL_FUNCTION_MEMBER_P (decl)
5435 	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5436 	  : DECL_FRIEND_CONTEXT (decl)
5437 	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5438 	  : false)
5439       /* And, if it was a member function, it really was defined in
5440 	 the scope of the class.  */
5441       && (!DECL_FUNCTION_MEMBER_P (decl)
5442 	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
5443     /* We already checked these parameters when the template was
5444        declared, so there's no need to do it again now.  This function
5445        was defined in class scope, but we're processing its body now
5446        that the class is complete.  */
5447     return true;
5448 
5449   /* Core issue 226 (C++0x only): the following only applies to class
5450      templates.  */
5451   if (is_primary
5452       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5453     {
5454       /* [temp.param]
5455 
5456          If a template-parameter has a default template-argument, all
5457          subsequent template-parameters shall have a default
5458          template-argument supplied.  */
5459       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5460         {
5461           tree inner_parms = TREE_VALUE (parm_level);
5462           int ntparms = TREE_VEC_LENGTH (inner_parms);
5463           int seen_def_arg_p = 0;
5464           int i;
5465 
5466           for (i = 0; i < ntparms; ++i)
5467             {
5468               tree parm = TREE_VEC_ELT (inner_parms, i);
5469 
5470               if (parm == error_mark_node)
5471                 continue;
5472 
5473               if (TREE_PURPOSE (parm))
5474                 seen_def_arg_p = 1;
5475               else if (seen_def_arg_p
5476 		       && !template_parameter_pack_p (TREE_VALUE (parm)))
5477                 {
5478                   error ("no default argument for %qD", TREE_VALUE (parm));
5479                   /* For better subsequent error-recovery, we indicate that
5480                      there should have been a default argument.  */
5481                   TREE_PURPOSE (parm) = error_mark_node;
5482                   no_errors = false;
5483                 }
5484 	      else if (!is_partial
5485 		       && !is_friend_decl
5486 		       /* Don't complain about an enclosing partial
5487 			  specialization.  */
5488 		       && parm_level == parms
5489 		       && TREE_CODE (decl) == TYPE_DECL
5490 		       && i < ntparms - 1
5491 		       && template_parameter_pack_p (TREE_VALUE (parm))
5492 		       /* A fixed parameter pack will be partially
5493 			  instantiated into a fixed length list.  */
5494 		       && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5495 		{
5496 		  /* A primary class template can only have one
5497 		     parameter pack, at the end of the template
5498 		     parameter list.  */
5499 
5500 		  error ("parameter pack %q+D must be at the end of the"
5501 			 " template parameter list", TREE_VALUE (parm));
5502 
5503 		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5504 		    = error_mark_node;
5505 		  no_errors = false;
5506 		}
5507             }
5508         }
5509     }
5510 
5511   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5512       || is_partial
5513       || !is_primary
5514       || is_friend_decl)
5515     /* For an ordinary class template, default template arguments are
5516        allowed at the innermost level, e.g.:
5517 	 template <class T = int>
5518 	 struct S {};
5519        but, in a partial specialization, they're not allowed even
5520        there, as we have in [temp.class.spec]:
5521 
5522 	 The template parameter list of a specialization shall not
5523 	 contain default template argument values.
5524 
5525        So, for a partial specialization, or for a function template
5526        (in C++98/C++03), we look at all of them.  */
5527     ;
5528   else
5529     /* But, for a primary class template that is not a partial
5530        specialization we look at all template parameters except the
5531        innermost ones.  */
5532     parms = TREE_CHAIN (parms);
5533 
5534   /* Figure out what error message to issue.  */
5535   if (is_friend_decl == 2)
5536     msg = G_("default template arguments may not be used in function template "
5537 	     "friend re-declaration");
5538   else if (is_friend_decl)
5539     msg = G_("default template arguments may not be used in template "
5540 	     "friend declarations");
5541   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5542     msg = G_("default template arguments may not be used in function templates "
5543 	     "without %<-std=c++11%> or %<-std=gnu++11%>");
5544   else if (is_partial)
5545     msg = G_("default template arguments may not be used in "
5546 	     "partial specializations");
5547   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5548     msg = G_("default argument for template parameter for class enclosing %qD");
5549   else
5550     /* Per [temp.param]/9, "A default template-argument shall not be
5551        specified in the template-parameter-lists of the definition of
5552        a member of a class template that appears outside of the member's
5553        class.", thus if we aren't handling a member of a class template
5554        there is no need to examine the parameters.  */
5555     return true;
5556 
5557   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5558     /* If we're inside a class definition, there's no need to
5559        examine the parameters to the class itself.  On the one
5560        hand, they will be checked when the class is defined, and,
5561        on the other, default arguments are valid in things like:
5562 	 template <class T = double>
5563 	 struct S { template <class U> void f(U); };
5564        Here the default argument for `S' has no bearing on the
5565        declaration of `f'.  */
5566     last_level_to_check = template_class_depth (current_class_type) + 1;
5567   else
5568     /* Check everything.  */
5569     last_level_to_check = 0;
5570 
5571   for (parm_level = parms;
5572        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5573        parm_level = TREE_CHAIN (parm_level))
5574     {
5575       tree inner_parms = TREE_VALUE (parm_level);
5576       int i;
5577       int ntparms;
5578 
5579       ntparms = TREE_VEC_LENGTH (inner_parms);
5580       for (i = 0; i < ntparms; ++i)
5581         {
5582           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5583             continue;
5584 
5585 	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5586 	    {
5587 	      if (msg)
5588 	        {
5589                   no_errors = false;
5590                   if (is_friend_decl == 2)
5591                     return no_errors;
5592 
5593 		  error (msg, decl);
5594 		  msg = 0;
5595 	        }
5596 
5597 	      /* Clear out the default argument so that we are not
5598 	         confused later.  */
5599 	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5600 	    }
5601         }
5602 
5603       /* At this point, if we're still interested in issuing messages,
5604 	 they must apply to classes surrounding the object declared.  */
5605       if (msg)
5606 	msg = G_("default argument for template parameter for class "
5607 		 "enclosing %qD");
5608     }
5609 
5610   return no_errors;
5611 }
5612 
5613 /* Worker for push_template_decl_real, called via
5614    for_each_template_parm.  DATA is really an int, indicating the
5615    level of the parameters we are interested in.  If T is a template
5616    parameter of that level, return nonzero.  */
5617 
5618 static int
template_parm_this_level_p(tree t,void * data)5619 template_parm_this_level_p (tree t, void* data)
5620 {
5621   int this_level = *(int *)data;
5622   int level;
5623 
5624   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5625     level = TEMPLATE_PARM_LEVEL (t);
5626   else
5627     level = TEMPLATE_TYPE_LEVEL (t);
5628   return level == this_level;
5629 }
5630 
5631 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5632    DATA is really an int, indicating the innermost outer level of parameters.
5633    If T is a template parameter of that level or further out, return
5634    nonzero.  */
5635 
5636 static int
template_parm_outer_level(tree t,void * data)5637 template_parm_outer_level (tree t, void *data)
5638 {
5639   int this_level = *(int *)data;
5640   int level;
5641 
5642   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5643     level = TEMPLATE_PARM_LEVEL (t);
5644   else
5645     level = TEMPLATE_TYPE_LEVEL (t);
5646   return level <= this_level;
5647 }
5648 
5649 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5650    parameters given by current_template_args, or reuses a
5651    previously existing one, if appropriate.  Returns the DECL, or an
5652    equivalent one, if it is replaced via a call to duplicate_decls.
5653 
5654    If IS_FRIEND is true, DECL is a friend declaration.  */
5655 
5656 tree
push_template_decl_real(tree decl,bool is_friend)5657 push_template_decl_real (tree decl, bool is_friend)
5658 {
5659   tree tmpl;
5660   tree args;
5661   tree info;
5662   tree ctx;
5663   bool is_primary;
5664   bool is_partial;
5665   int new_template_p = 0;
5666   /* True if the template is a member template, in the sense of
5667      [temp.mem].  */
5668   bool member_template_p = false;
5669 
5670   if (decl == error_mark_node || !current_template_parms)
5671     return error_mark_node;
5672 
5673   /* See if this is a partial specialization.  */
5674   is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5675 		 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5676 		 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5677 		|| (VAR_P (decl)
5678 		    && DECL_LANG_SPECIFIC (decl)
5679 		    && DECL_TEMPLATE_SPECIALIZATION (decl)
5680 		    && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5681 
5682   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
5683     is_friend = true;
5684 
5685   if (is_friend)
5686     /* For a friend, we want the context of the friend, not
5687        the type of which it is a friend.  */
5688     ctx = CP_DECL_CONTEXT (decl);
5689   else if (CP_DECL_CONTEXT (decl)
5690 	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5691     /* In the case of a virtual function, we want the class in which
5692        it is defined.  */
5693     ctx = CP_DECL_CONTEXT (decl);
5694   else
5695     /* Otherwise, if we're currently defining some class, the DECL
5696        is assumed to be a member of the class.  */
5697     ctx = current_scope ();
5698 
5699   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5700     ctx = NULL_TREE;
5701 
5702   if (!DECL_CONTEXT (decl))
5703     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5704 
5705   /* See if this is a primary template.  */
5706   if (is_friend && ctx
5707       && uses_template_parms_level (ctx, processing_template_decl))
5708     /* A friend template that specifies a class context, i.e.
5709          template <typename T> friend void A<T>::f();
5710        is not primary.  */
5711     is_primary = false;
5712   else if (TREE_CODE (decl) == TYPE_DECL
5713 	   && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5714     is_primary = false;
5715   else
5716     is_primary = template_parm_scope_p ();
5717 
5718   if (is_primary)
5719     {
5720       warning (OPT_Wtemplates, "template %qD declared", decl);
5721 
5722       if (DECL_CLASS_SCOPE_P (decl))
5723 	member_template_p = true;
5724       if (TREE_CODE (decl) == TYPE_DECL
5725 	  && IDENTIFIER_ANON_P (DECL_NAME (decl)))
5726 	{
5727 	  error ("template class without a name");
5728 	  return error_mark_node;
5729 	}
5730       else if (TREE_CODE (decl) == FUNCTION_DECL)
5731 	{
5732 	  if (member_template_p)
5733 	    {
5734 	      if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5735 		error ("member template %qD may not have virt-specifiers", decl);
5736 	    }
5737 	  if (DECL_DESTRUCTOR_P (decl))
5738 	    {
5739 	      /* [temp.mem]
5740 
5741 		 A destructor shall not be a member template.  */
5742 	      error_at (DECL_SOURCE_LOCATION (decl),
5743 			"destructor %qD declared as member template", decl);
5744 	      return error_mark_node;
5745 	    }
5746 	  if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5747 	      && (!prototype_p (TREE_TYPE (decl))
5748 		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5749 		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5750 		  || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5751 		      == void_list_node)))
5752 	    {
5753 	      /* [basic.stc.dynamic.allocation]
5754 
5755 		 An allocation function can be a function
5756 		 template. ... Template allocation functions shall
5757 		 have two or more parameters.  */
5758 	      error ("invalid template declaration of %qD", decl);
5759 	      return error_mark_node;
5760 	    }
5761 	}
5762       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5763 	       && CLASS_TYPE_P (TREE_TYPE (decl)))
5764 	{
5765 	  /* Class template, set TEMPLATE_TYPE_PARM_FOR_CLASS.  */
5766 	  tree parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5767 	  for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
5768 	    {
5769 	      tree t = TREE_VALUE (TREE_VEC_ELT (parms, i));
5770 	      if (TREE_CODE (t) == TYPE_DECL)
5771 		t = TREE_TYPE (t);
5772 	      if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
5773 		TEMPLATE_TYPE_PARM_FOR_CLASS (t) = true;
5774 	    }
5775 	}
5776       else if (TREE_CODE (decl) == TYPE_DECL
5777 	       && TYPE_DECL_ALIAS_P (decl))
5778 	/* alias-declaration */
5779 	gcc_assert (!DECL_ARTIFICIAL (decl));
5780       else if (VAR_P (decl))
5781 	/* C++14 variable template. */;
5782       else if (TREE_CODE (decl) == CONCEPT_DECL)
5783 	/* C++2a concept definitions.  */;
5784       else
5785 	{
5786 	  error ("template declaration of %q#D", decl);
5787 	  return error_mark_node;
5788 	}
5789     }
5790 
5791   /* Check to see that the rules regarding the use of default
5792      arguments are not being violated.  We check args for a friend
5793      functions when we know whether it's a definition, introducing
5794      declaration or re-declaration.  */
5795   if (!is_friend || TREE_CODE (decl) != FUNCTION_DECL)
5796     check_default_tmpl_args (decl, current_template_parms,
5797 			     is_primary, is_partial, is_friend);
5798 
5799   /* Ensure that there are no parameter packs in the type of this
5800      declaration that have not been expanded.  */
5801   if (TREE_CODE (decl) == FUNCTION_DECL)
5802     {
5803       /* Check each of the arguments individually to see if there are
5804          any bare parameter packs.  */
5805       tree type = TREE_TYPE (decl);
5806       tree arg = DECL_ARGUMENTS (decl);
5807       tree argtype = TYPE_ARG_TYPES (type);
5808 
5809       while (arg && argtype)
5810         {
5811           if (!DECL_PACK_P (arg)
5812               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5813             {
5814             /* This is a PARM_DECL that contains unexpanded parameter
5815                packs. We have already complained about this in the
5816                check_for_bare_parameter_packs call, so just replace
5817                these types with ERROR_MARK_NODE.  */
5818               TREE_TYPE (arg) = error_mark_node;
5819               TREE_VALUE (argtype) = error_mark_node;
5820             }
5821 
5822           arg = DECL_CHAIN (arg);
5823           argtype = TREE_CHAIN (argtype);
5824         }
5825 
5826       /* Check for bare parameter packs in the return type and the
5827          exception specifiers.  */
5828       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5829 	/* Errors were already issued, set return type to int
5830 	   as the frontend doesn't expect error_mark_node as
5831 	   the return type.  */
5832 	TREE_TYPE (type) = integer_type_node;
5833       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5834 	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5835     }
5836   else if (check_for_bare_parameter_packs (is_typedef_decl (decl)
5837 					   ? DECL_ORIGINAL_TYPE (decl)
5838 					   : TREE_TYPE (decl)))
5839     {
5840       TREE_TYPE (decl) = error_mark_node;
5841       return error_mark_node;
5842     }
5843 
5844   if (is_partial)
5845     return process_partial_specialization (decl);
5846 
5847   args = current_template_args ();
5848 
5849   if (!ctx
5850       || TREE_CODE (ctx) == FUNCTION_DECL
5851       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5852       || (TREE_CODE (decl) == TYPE_DECL
5853 	  && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5854       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
5855     {
5856       if (DECL_LANG_SPECIFIC (decl)
5857 	  && DECL_TEMPLATE_INFO (decl)
5858 	  && DECL_TI_TEMPLATE (decl))
5859 	tmpl = DECL_TI_TEMPLATE (decl);
5860       /* If DECL is a TYPE_DECL for a class-template, then there won't
5861 	 be DECL_LANG_SPECIFIC.  The information equivalent to
5862 	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
5863       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5864 	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5865 	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5866 	{
5867 	  /* Since a template declaration already existed for this
5868 	     class-type, we must be redeclaring it here.  Make sure
5869 	     that the redeclaration is valid.  */
5870 	  redeclare_class_template (TREE_TYPE (decl),
5871 				    current_template_parms,
5872 				    current_template_constraints ());
5873 	  /* We don't need to create a new TEMPLATE_DECL; just use the
5874 	     one we already had.  */
5875 	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5876 	}
5877       else
5878 	{
5879 	  tmpl = build_template_decl (decl, current_template_parms,
5880 				      member_template_p);
5881 	  new_template_p = 1;
5882 
5883 	  if (DECL_LANG_SPECIFIC (decl)
5884 	      && DECL_TEMPLATE_SPECIALIZATION (decl))
5885 	    {
5886 	      /* A specialization of a member template of a template
5887 		 class.  */
5888 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5889 	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5890 	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5891 	    }
5892 	}
5893     }
5894   else
5895     {
5896       tree a, t, current, parms;
5897       int i;
5898       tree tinfo = get_template_info (decl);
5899 
5900       if (!tinfo)
5901 	{
5902 	  error ("template definition of non-template %q#D", decl);
5903 	  return error_mark_node;
5904 	}
5905 
5906       tmpl = TI_TEMPLATE (tinfo);
5907 
5908       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5909 	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5910 	  && DECL_TEMPLATE_SPECIALIZATION (decl)
5911 	  && DECL_MEMBER_TEMPLATE_P (tmpl))
5912 	{
5913 	  tree new_tmpl;
5914 
5915 	  /* The declaration is a specialization of a member
5916 	     template, declared outside the class.  Therefore, the
5917 	     innermost template arguments will be NULL, so we
5918 	     replace them with the arguments determined by the
5919 	     earlier call to check_explicit_specialization.  */
5920 	  args = DECL_TI_ARGS (decl);
5921 
5922 	  new_tmpl
5923 	    = build_template_decl (decl, current_template_parms,
5924 				   member_template_p);
5925 	  DECL_TEMPLATE_RESULT (new_tmpl) = decl;
5926 	  TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
5927 	  DECL_TI_TEMPLATE (decl) = new_tmpl;
5928 	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5929 	  DECL_TEMPLATE_INFO (new_tmpl)
5930 	    = build_template_info (tmpl, args);
5931 
5932 	  register_specialization (new_tmpl,
5933 				   most_general_template (tmpl),
5934 				   args,
5935 				   is_friend, 0);
5936 	  return decl;
5937 	}
5938 
5939       /* Make sure the template headers we got make sense.  */
5940 
5941       parms = DECL_TEMPLATE_PARMS (tmpl);
5942       i = TMPL_PARMS_DEPTH (parms);
5943       if (TMPL_ARGS_DEPTH (args) != i)
5944 	{
5945 	  error ("expected %d levels of template parms for %q#D, got %d",
5946 		 i, decl, TMPL_ARGS_DEPTH (args));
5947 	  DECL_INTERFACE_KNOWN (decl) = 1;
5948 	  return error_mark_node;
5949 	}
5950       else
5951 	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5952 	  {
5953 	    a = TMPL_ARGS_LEVEL (args, i);
5954 	    t = INNERMOST_TEMPLATE_PARMS (parms);
5955 
5956 	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5957 	      {
5958 		if (current == decl)
5959 		  error ("got %d template parameters for %q#D",
5960 			 TREE_VEC_LENGTH (a), decl);
5961 		else
5962 		  error ("got %d template parameters for %q#T",
5963 			 TREE_VEC_LENGTH (a), current);
5964 		error ("  but %d required", TREE_VEC_LENGTH (t));
5965 		/* Avoid crash in import_export_decl.  */
5966 		DECL_INTERFACE_KNOWN (decl) = 1;
5967 		return error_mark_node;
5968 	      }
5969 
5970 	    if (current == decl)
5971 	      current = ctx;
5972 	    else if (current == NULL_TREE)
5973 	      /* Can happen in erroneous input.  */
5974 	      break;
5975 	    else
5976 	      current = get_containing_scope (current);
5977 	  }
5978 
5979       /* Check that the parms are used in the appropriate qualifying scopes
5980 	 in the declarator.  */
5981       if (!comp_template_args
5982 	  (TI_ARGS (tinfo),
5983 	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5984 	{
5985 	  error ("template arguments to %qD do not match original "
5986 		 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
5987 	  if (!uses_template_parms (TI_ARGS (tinfo)))
5988 	    inform (input_location, "use %<template<>%> for"
5989 		    " an explicit specialization");
5990 	  /* Avoid crash in import_export_decl.  */
5991 	  DECL_INTERFACE_KNOWN (decl) = 1;
5992 	  return error_mark_node;
5993 	}
5994     }
5995 
5996   DECL_TEMPLATE_RESULT (tmpl) = decl;
5997   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5998 
5999   /* Push template declarations for global functions and types.  Note
6000      that we do not try to push a global template friend declared in a
6001      template class; such a thing may well depend on the template
6002      parameters of the class.  */
6003   if (new_template_p && !ctx
6004       && !(is_friend && template_class_depth (current_class_type) > 0))
6005     {
6006       tmpl = pushdecl_namespace_level (tmpl, is_friend);
6007       if (tmpl == error_mark_node)
6008 	return error_mark_node;
6009 
6010       /* Hide template friend classes that haven't been declared yet.  */
6011       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
6012 	{
6013 	  DECL_ANTICIPATED (tmpl) = 1;
6014 	  DECL_FRIEND_P (tmpl) = 1;
6015 	}
6016     }
6017 
6018   if (is_primary)
6019     {
6020       tree parms = DECL_TEMPLATE_PARMS (tmpl);
6021 
6022       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6023 
6024       /* Give template template parms a DECL_CONTEXT of the template
6025 	 for which they are a parameter.  */
6026       parms = INNERMOST_TEMPLATE_PARMS (parms);
6027       for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
6028 	{
6029 	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6030 	  if (TREE_CODE (parm) == TEMPLATE_DECL)
6031 	    DECL_CONTEXT (parm) = tmpl;
6032 	}
6033 
6034       if (TREE_CODE (decl) == TYPE_DECL
6035 	  && TYPE_DECL_ALIAS_P (decl))
6036 	{
6037 	  if (tree constr
6038 	      = TEMPLATE_PARMS_CONSTRAINTS (DECL_TEMPLATE_PARMS (tmpl)))
6039 	    {
6040 	      /* ??? Why don't we do this here for all templates?  */
6041 	      constr = build_constraints (constr, NULL_TREE);
6042 	      set_constraints (decl, constr);
6043 	    }
6044 	  if (complex_alias_template_p (tmpl))
6045 	    TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
6046 	}
6047     }
6048 
6049   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
6050      back to its most general template.  If TMPL is a specialization,
6051      ARGS may only have the innermost set of arguments.  Add the missing
6052      argument levels if necessary.  */
6053   if (DECL_TEMPLATE_INFO (tmpl))
6054     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
6055 
6056   info = build_template_info (tmpl, args);
6057 
6058   if (DECL_IMPLICIT_TYPEDEF_P (decl))
6059     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
6060   else
6061     {
6062       if (is_primary)
6063 	retrofit_lang_decl (decl);
6064       if (DECL_LANG_SPECIFIC (decl))
6065 	DECL_TEMPLATE_INFO (decl) = info;
6066     }
6067 
6068   if (flag_implicit_templates
6069       && !is_friend
6070       && TREE_PUBLIC (decl)
6071       && VAR_OR_FUNCTION_DECL_P (decl))
6072     /* Set DECL_COMDAT on template instantiations; if we force
6073        them to be emitted by explicit instantiation,
6074        mark_needed will tell cgraph to do the right thing.  */
6075     DECL_COMDAT (decl) = true;
6076 
6077   return DECL_TEMPLATE_RESULT (tmpl);
6078 }
6079 
6080 tree
push_template_decl(tree decl)6081 push_template_decl (tree decl)
6082 {
6083   return push_template_decl_real (decl, false);
6084 }
6085 
6086 /* FN is an inheriting constructor that inherits from the constructor
6087    template INHERITED; turn FN into a constructor template with a matching
6088    template header.  */
6089 
6090 tree
add_inherited_template_parms(tree fn,tree inherited)6091 add_inherited_template_parms (tree fn, tree inherited)
6092 {
6093   tree inner_parms
6094     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
6095   inner_parms = copy_node (inner_parms);
6096   tree parms
6097     = tree_cons (size_int (processing_template_decl + 1),
6098 		 inner_parms, current_template_parms);
6099   tree tmpl = build_template_decl (fn, parms, /*member*/true);
6100   tree args = template_parms_to_args (parms);
6101   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
6102   TREE_TYPE (tmpl) = TREE_TYPE (fn);
6103   DECL_TEMPLATE_RESULT (tmpl) = fn;
6104   DECL_ARTIFICIAL (tmpl) = true;
6105   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
6106   return tmpl;
6107 }
6108 
6109 /* Called when a class template TYPE is redeclared with the indicated
6110    template PARMS, e.g.:
6111 
6112      template <class T> struct S;
6113      template <class T> struct S {};  */
6114 
6115 bool
redeclare_class_template(tree type,tree parms,tree cons)6116 redeclare_class_template (tree type, tree parms, tree cons)
6117 {
6118   tree tmpl;
6119   tree tmpl_parms;
6120   int i;
6121 
6122   if (!TYPE_TEMPLATE_INFO (type))
6123     {
6124       error ("%qT is not a template type", type);
6125       return false;
6126     }
6127 
6128   tmpl = TYPE_TI_TEMPLATE (type);
6129   if (!PRIMARY_TEMPLATE_P (tmpl))
6130     /* The type is nested in some template class.  Nothing to worry
6131        about here; there are no new template parameters for the nested
6132        type.  */
6133     return true;
6134 
6135   if (!parms)
6136     {
6137       error ("template specifiers not specified in declaration of %qD",
6138 	     tmpl);
6139       return false;
6140     }
6141 
6142   parms = INNERMOST_TEMPLATE_PARMS (parms);
6143   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
6144 
6145   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
6146     {
6147       error_n (input_location, TREE_VEC_LENGTH (parms),
6148                "redeclared with %d template parameter",
6149                "redeclared with %d template parameters",
6150                TREE_VEC_LENGTH (parms));
6151       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
6152                 "previous declaration %qD used %d template parameter",
6153                 "previous declaration %qD used %d template parameters",
6154                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
6155       return false;
6156     }
6157 
6158   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
6159     {
6160       tree tmpl_parm;
6161       tree parm;
6162       tree tmpl_default;
6163       tree parm_default;
6164 
6165       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
6166           || TREE_VEC_ELT (parms, i) == error_mark_node)
6167         continue;
6168 
6169       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
6170       if (error_operand_p (tmpl_parm))
6171 	return false;
6172 
6173       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
6174       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
6175       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
6176 
6177       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
6178 	 TEMPLATE_DECL.  */
6179       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
6180 	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
6181 	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
6182 	  || (TREE_CODE (tmpl_parm) != PARM_DECL
6183 	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
6184 		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
6185 	  || (TREE_CODE (tmpl_parm) == PARM_DECL
6186 	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
6187 		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
6188 	{
6189 	  auto_diagnostic_group d;
6190 	  error ("template parameter %q+#D", tmpl_parm);
6191 	  inform (input_location, "redeclared here as %q#D", parm);
6192 	  return false;
6193 	}
6194 
6195       /* The parameters can be declared to introduce different
6196 	 constraints.  */
6197       tree p1 = TREE_VEC_ELT (tmpl_parms, i);
6198       tree p2 = TREE_VEC_ELT (parms, i);
6199       if (!template_parameter_constraints_equivalent_p (p1, p2))
6200 	{
6201 	  auto_diagnostic_group d;
6202 	  error ("declaration of template parameter %q+#D with different "
6203 		 "constraints", parm);
6204 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
6205 		  "original declaration appeared here");
6206 	  return false;
6207 	}
6208 
6209       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
6210 	{
6211 	  /* We have in [temp.param]:
6212 
6213 	     A template-parameter may not be given default arguments
6214 	     by two different declarations in the same scope.  */
6215 	  auto_diagnostic_group d;
6216 	  error_at (input_location, "redefinition of default argument for %q#D", parm);
6217 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
6218 		  "original definition appeared here");
6219 	  return false;
6220 	}
6221 
6222       if (parm_default != NULL_TREE)
6223 	/* Update the previous template parameters (which are the ones
6224 	   that will really count) with the new default value.  */
6225 	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
6226       else if (tmpl_default != NULL_TREE)
6227 	/* Update the new parameters, too; they'll be used as the
6228 	   parameters for any members.  */
6229 	TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
6230 
6231       /* Give each template template parm in this redeclaration a
6232 	 DECL_CONTEXT of the template for which they are a parameter.  */
6233       if (TREE_CODE (parm) == TEMPLATE_DECL)
6234 	{
6235 	  gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
6236 	  DECL_CONTEXT (parm) = tmpl;
6237 	}
6238 
6239       if (TREE_CODE (parm) == TYPE_DECL)
6240 	TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (parm)) = true;
6241     }
6242 
6243   tree ci = get_constraints (tmpl);
6244   tree req1 = ci ? CI_TEMPLATE_REQS (ci) : NULL_TREE;
6245   tree req2 = cons ? CI_TEMPLATE_REQS (cons) : NULL_TREE;
6246 
6247   /* Two classes with different constraints declare different entities.  */
6248   if (!cp_tree_equal (req1, req2))
6249     {
6250       auto_diagnostic_group d;
6251       error_at (input_location, "redeclaration %q#D with different "
6252                                 "constraints", tmpl);
6253       inform (DECL_SOURCE_LOCATION (tmpl),
6254               "original declaration appeared here");
6255       return false;
6256     }
6257 
6258     return true;
6259 }
6260 
6261 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
6262    to be used when the caller has already checked
6263    (processing_template_decl
6264     && !instantiation_dependent_expression_p (expr)
6265     && potential_constant_expression (expr))
6266    and cleared processing_template_decl.  */
6267 
6268 tree
instantiate_non_dependent_expr_internal(tree expr,tsubst_flags_t complain)6269 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6270 {
6271   return tsubst_copy_and_build (expr,
6272 				/*args=*/NULL_TREE,
6273 				complain,
6274 				/*in_decl=*/NULL_TREE,
6275 				/*function_p=*/false,
6276 				/*integral_constant_expression_p=*/true);
6277 }
6278 
6279 /* Simplify EXPR if it is a non-dependent expression.  Returns the
6280    (possibly simplified) expression.  */
6281 
6282 tree
instantiate_non_dependent_expr_sfinae(tree expr,tsubst_flags_t complain)6283 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6284 {
6285   if (expr == NULL_TREE)
6286     return NULL_TREE;
6287 
6288   /* If we're in a template, but EXPR isn't value dependent, simplify
6289      it.  We're supposed to treat:
6290 
6291        template <typename T> void f(T[1 + 1]);
6292        template <typename T> void f(T[2]);
6293 
6294      as two declarations of the same function, for example.  */
6295   if (processing_template_decl
6296       && is_nondependent_constant_expression (expr))
6297     {
6298       processing_template_decl_sentinel s;
6299       expr = instantiate_non_dependent_expr_internal (expr, complain);
6300     }
6301   return expr;
6302 }
6303 
6304 tree
instantiate_non_dependent_expr(tree expr)6305 instantiate_non_dependent_expr (tree expr)
6306 {
6307   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6308 }
6309 
6310 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
6311    an uninstantiated expression.  */
6312 
6313 tree
instantiate_non_dependent_or_null(tree expr)6314 instantiate_non_dependent_or_null (tree expr)
6315 {
6316   if (expr == NULL_TREE)
6317     return NULL_TREE;
6318   if (processing_template_decl)
6319     {
6320       if (!is_nondependent_constant_expression (expr))
6321 	expr = NULL_TREE;
6322       else
6323 	{
6324 	  processing_template_decl_sentinel s;
6325 	  expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6326 	}
6327     }
6328   return expr;
6329 }
6330 
6331 /* True iff T is a specialization of a variable template.  */
6332 
6333 bool
variable_template_specialization_p(tree t)6334 variable_template_specialization_p (tree t)
6335 {
6336   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6337     return false;
6338   tree tmpl = DECL_TI_TEMPLATE (t);
6339   return variable_template_p (tmpl);
6340 }
6341 
6342 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6343    template declaration, or a TYPE_DECL for an alias declaration.  */
6344 
6345 bool
alias_type_or_template_p(tree t)6346 alias_type_or_template_p (tree t)
6347 {
6348   if (t == NULL_TREE)
6349     return false;
6350   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6351 	  || (TYPE_P (t)
6352 	      && TYPE_NAME (t)
6353 	      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6354 	  || DECL_ALIAS_TEMPLATE_P (t));
6355 }
6356 
6357 /* If T is a specialization of an alias template, return it; otherwise return
6358    NULL_TREE.  If TRANSPARENT_TYPEDEFS is true, look through other aliases.  */
6359 
6360 tree
alias_template_specialization_p(const_tree t,bool transparent_typedefs)6361 alias_template_specialization_p (const_tree t,
6362 				 bool transparent_typedefs)
6363 {
6364   if (!TYPE_P (t))
6365     return NULL_TREE;
6366 
6367   /* It's an alias template specialization if it's an alias and its
6368      TYPE_NAME is a specialization of a primary template.  */
6369   if (typedef_variant_p (t))
6370     {
6371       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6372 	if (PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo)))
6373 	  return CONST_CAST_TREE (t);
6374       if (transparent_typedefs)
6375 	return alias_template_specialization_p (DECL_ORIGINAL_TYPE
6376 						(TYPE_NAME (t)),
6377 						transparent_typedefs);
6378     }
6379 
6380   return NULL_TREE;
6381 }
6382 
6383 /* An alias template is complex from a SFINAE perspective if a template-id
6384    using that alias can be ill-formed when the expansion is not, as with
6385    the void_t template.  We determine this by checking whether the
6386    expansion for the alias template uses all its template parameters.  */
6387 
6388 struct uses_all_template_parms_data
6389 {
6390   int level;
6391   bool *seen;
6392 };
6393 
6394 static int
uses_all_template_parms_r(tree t,void * data_)6395 uses_all_template_parms_r (tree t, void *data_)
6396 {
6397   struct uses_all_template_parms_data &data
6398     = *(struct uses_all_template_parms_data*)data_;
6399   tree idx = get_template_parm_index (t);
6400 
6401   if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6402     data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6403   return 0;
6404 }
6405 
6406 /* for_each_template_parm any_fn callback for complex_alias_template_p.  */
6407 
6408 static int
complex_pack_expansion_r(tree t,void * data_)6409 complex_pack_expansion_r (tree t, void *data_)
6410 {
6411   /* An alias template with a pack expansion that expands a pack from the
6412      enclosing class needs to be considered complex, to avoid confusion with
6413      the same pack being used as an argument to the alias's own template
6414      parameter (91966).  */
6415   if (!PACK_EXPANSION_P (t))
6416     return 0;
6417   struct uses_all_template_parms_data &data
6418     = *(struct uses_all_template_parms_data*)data_;
6419   for (tree pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
6420        pack = TREE_CHAIN (pack))
6421     {
6422       tree parm_pack = TREE_VALUE (pack);
6423       if (!TEMPLATE_PARM_P (parm_pack))
6424 	continue;
6425       int idx, level;
6426       template_parm_level_and_index (parm_pack, &level, &idx);
6427       if (level < data.level)
6428 	return 1;
6429     }
6430   return 0;
6431 }
6432 
6433 static bool
complex_alias_template_p(const_tree tmpl)6434 complex_alias_template_p (const_tree tmpl)
6435 {
6436   /* A renaming alias isn't complex.  */
6437   if (get_underlying_template (CONST_CAST_TREE (tmpl)) != tmpl)
6438     return false;
6439 
6440   /* Any other constrained alias is complex.  */
6441   if (get_constraints (tmpl))
6442     return true;
6443 
6444   struct uses_all_template_parms_data data;
6445   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6446   tree parms = DECL_TEMPLATE_PARMS (tmpl);
6447   data.level = TMPL_PARMS_DEPTH (parms);
6448   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6449   data.seen = XALLOCAVEC (bool, len);
6450   for (int i = 0; i < len; ++i)
6451     data.seen[i] = false;
6452 
6453   if (for_each_template_parm (pat, uses_all_template_parms_r, &data,
6454 			      NULL, true, complex_pack_expansion_r))
6455     return true;
6456   for (int i = 0; i < len; ++i)
6457     if (!data.seen[i])
6458       return true;
6459   return false;
6460 }
6461 
6462 /* If T is a specialization of a complex alias template with dependent
6463    template-arguments, return it; otherwise return NULL_TREE.  If T is a
6464    typedef to such a specialization, return the specialization.  */
6465 
6466 tree
dependent_alias_template_spec_p(const_tree t,bool transparent_typedefs)6467 dependent_alias_template_spec_p (const_tree t, bool transparent_typedefs)
6468 {
6469   if (!TYPE_P (t) || !typedef_variant_p (t))
6470     return NULL_TREE;
6471 
6472   tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6473   if (tinfo
6474       && TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo))
6475       && (any_dependent_template_arguments_p
6476 	  (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)))))
6477     return CONST_CAST_TREE (t);
6478 
6479   if (transparent_typedefs)
6480     {
6481       tree utype = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
6482       return dependent_alias_template_spec_p (utype, transparent_typedefs);
6483     }
6484 
6485   return NULL_TREE;
6486 }
6487 
6488 /* Return the number of innermost template parameters in TMPL.  */
6489 
6490 static int
num_innermost_template_parms(const_tree tmpl)6491 num_innermost_template_parms (const_tree tmpl)
6492 {
6493   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6494   return TREE_VEC_LENGTH (parms);
6495 }
6496 
6497 /* Return either TMPL or another template that it is equivalent to under DR
6498    1286: An alias that just changes the name of a template is equivalent to
6499    the other template.  */
6500 
6501 static tree
get_underlying_template(tree tmpl)6502 get_underlying_template (tree tmpl)
6503 {
6504   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6505   while (DECL_ALIAS_TEMPLATE_P (tmpl))
6506     {
6507       /* Determine if the alias is equivalent to an underlying template.  */
6508       tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6509       /* The underlying type may have been ill-formed. Don't proceed.  */
6510       if (!orig_type)
6511 	break;
6512       tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6513       if (!tinfo)
6514 	break;
6515 
6516       tree underlying = TI_TEMPLATE (tinfo);
6517       if (!PRIMARY_TEMPLATE_P (underlying)
6518 	  || (num_innermost_template_parms (tmpl)
6519 	      != num_innermost_template_parms (underlying)))
6520 	break;
6521 
6522       /* Does the alias add cv-quals?  */
6523       if (TYPE_QUALS (TREE_TYPE (underlying)) != TYPE_QUALS (TREE_TYPE (tmpl)))
6524 	break;
6525 
6526       tree alias_args = INNERMOST_TEMPLATE_ARGS (generic_targs_for (tmpl));
6527       if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6528 	break;
6529 
6530       /* If TMPL adds or changes any constraints, it isn't equivalent.  I think
6531 	 it's appropriate to treat a less-constrained alias as equivalent.  */
6532       if (!at_least_as_constrained (underlying, tmpl))
6533 	break;
6534 
6535       /* Alias is equivalent.  Strip it and repeat.  */
6536       tmpl = underlying;
6537     }
6538 
6539   return tmpl;
6540 }
6541 
6542 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6543    must be a reference-to-function or a pointer-to-function type, as specified
6544    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6545    and check that the resulting function has external linkage.  */
6546 
6547 static tree
convert_nontype_argument_function(tree type,tree expr,tsubst_flags_t complain)6548 convert_nontype_argument_function (tree type, tree expr,
6549 				   tsubst_flags_t complain)
6550 {
6551   tree fns = expr;
6552   tree fn, fn_no_ptr;
6553   linkage_kind linkage;
6554 
6555   fn = instantiate_type (type, fns, tf_none);
6556   if (fn == error_mark_node)
6557     return error_mark_node;
6558 
6559   if (value_dependent_expression_p (fn))
6560     goto accept;
6561 
6562   fn_no_ptr = strip_fnptr_conv (fn);
6563   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6564     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6565   if (BASELINK_P (fn_no_ptr))
6566     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6567 
6568   /* [temp.arg.nontype]/1
6569 
6570      A template-argument for a non-type, non-template template-parameter
6571      shall be one of:
6572      [...]
6573      -- the address of an object or function with external [C++11: or
6574         internal] linkage.  */
6575 
6576   STRIP_ANY_LOCATION_WRAPPER (fn_no_ptr);
6577   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6578     {
6579       if (complain & tf_error)
6580 	{
6581 	  location_t loc = cp_expr_loc_or_input_loc (expr);
6582 	  error_at (loc, "%qE is not a valid template argument for type %qT",
6583 		    expr, type);
6584 	  if (TYPE_PTR_P (type))
6585 	    inform (loc, "it must be the address of a function "
6586 		    "with external linkage");
6587 	  else
6588 	    inform (loc, "it must be the name of a function with "
6589 		    "external linkage");
6590 	}
6591       return NULL_TREE;
6592     }
6593 
6594   linkage = decl_linkage (fn_no_ptr);
6595   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6596     {
6597       if (complain & tf_error)
6598 	{
6599 	  location_t loc = cp_expr_loc_or_input_loc (expr);
6600 	  if (cxx_dialect >= cxx11)
6601 	    error_at (loc, "%qE is not a valid template argument for type "
6602 		      "%qT because %qD has no linkage",
6603 		      expr, type, fn_no_ptr);
6604 	  else
6605 	    error_at (loc, "%qE is not a valid template argument for type "
6606 		      "%qT because %qD does not have external linkage",
6607 		      expr, type, fn_no_ptr);
6608 	}
6609       return NULL_TREE;
6610     }
6611 
6612  accept:
6613   if (TYPE_REF_P (type))
6614     {
6615       if (REFERENCE_REF_P (fn))
6616 	fn = TREE_OPERAND (fn, 0);
6617       else
6618 	fn = build_address (fn);
6619     }
6620   if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6621     fn = build_nop (type, fn);
6622 
6623   return fn;
6624 }
6625 
6626 /* Subroutine of convert_nontype_argument.
6627    Check if EXPR of type TYPE is a valid pointer-to-member constant.
6628    Emit an error otherwise.  */
6629 
6630 static bool
check_valid_ptrmem_cst_expr(tree type,tree expr,tsubst_flags_t complain)6631 check_valid_ptrmem_cst_expr (tree type, tree expr,
6632 			     tsubst_flags_t complain)
6633 {
6634   tree orig_expr = expr;
6635   STRIP_NOPS (expr);
6636   if (null_ptr_cst_p (expr))
6637     return true;
6638   if (TREE_CODE (expr) == PTRMEM_CST
6639       && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6640 		      PTRMEM_CST_CLASS (expr)))
6641     return true;
6642   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6643     return true;
6644   if (processing_template_decl
6645       && TREE_CODE (expr) == ADDR_EXPR
6646       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6647     return true;
6648   if (complain & tf_error)
6649     {
6650       location_t loc = cp_expr_loc_or_input_loc (orig_expr);
6651       error_at (loc, "%qE is not a valid template argument for type %qT",
6652 		orig_expr, type);
6653       if (TREE_CODE (expr) != PTRMEM_CST)
6654 	inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6655       else
6656 	inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6657     }
6658   return false;
6659 }
6660 
6661 /* Returns TRUE iff the address of OP is value-dependent.
6662 
6663    14.6.2.4 [temp.dep.temp]:
6664    A non-integral non-type template-argument is dependent if its type is
6665    dependent or it has either of the following forms
6666      qualified-id
6667      & qualified-id
6668    and contains a nested-name-specifier which specifies a class-name that
6669    names a dependent type.
6670 
6671    We generalize this to just say that the address of a member of a
6672    dependent class is value-dependent; the above doesn't cover the
6673    address of a static data member named with an unqualified-id.  */
6674 
6675 static bool
has_value_dependent_address(tree op)6676 has_value_dependent_address (tree op)
6677 {
6678   STRIP_ANY_LOCATION_WRAPPER (op);
6679 
6680   /* We could use get_inner_reference here, but there's no need;
6681      this is only relevant for template non-type arguments, which
6682      can only be expressed as &id-expression.  */
6683   if (DECL_P (op))
6684     {
6685       tree ctx = CP_DECL_CONTEXT (op);
6686       if (TYPE_P (ctx) && dependent_type_p (ctx))
6687 	return true;
6688     }
6689 
6690   return false;
6691 }
6692 
6693 /* The next set of functions are used for providing helpful explanatory
6694    diagnostics for failed overload resolution.  Their messages should be
6695    indented by two spaces for consistency with the messages in
6696    call.c  */
6697 
6698 static int
unify_success(bool)6699 unify_success (bool /*explain_p*/)
6700 {
6701   return 0;
6702 }
6703 
6704 /* Other failure functions should call this one, to provide a single function
6705    for setting a breakpoint on.  */
6706 
6707 static int
unify_invalid(bool)6708 unify_invalid (bool /*explain_p*/)
6709 {
6710   return 1;
6711 }
6712 
6713 static int
unify_parameter_deduction_failure(bool explain_p,tree parm)6714 unify_parameter_deduction_failure (bool explain_p, tree parm)
6715 {
6716   if (explain_p)
6717     inform (input_location,
6718 	    "  couldn%'t deduce template parameter %qD", parm);
6719   return unify_invalid (explain_p);
6720 }
6721 
6722 static int
unify_cv_qual_mismatch(bool explain_p,tree parm,tree arg)6723 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6724 {
6725   if (explain_p)
6726     inform (input_location,
6727 	    "  types %qT and %qT have incompatible cv-qualifiers",
6728 	    parm, arg);
6729   return unify_invalid (explain_p);
6730 }
6731 
6732 static int
unify_type_mismatch(bool explain_p,tree parm,tree arg)6733 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6734 {
6735   if (explain_p)
6736     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6737   return unify_invalid (explain_p);
6738 }
6739 
6740 static int
unify_parameter_pack_mismatch(bool explain_p,tree parm,tree arg)6741 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6742 {
6743   if (explain_p)
6744     inform (input_location,
6745 	    "  template parameter %qD is not a parameter pack, but "
6746 	    "argument %qD is",
6747 	    parm, arg);
6748   return unify_invalid (explain_p);
6749 }
6750 
6751 static int
unify_ptrmem_cst_mismatch(bool explain_p,tree parm,tree arg)6752 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6753 {
6754   if (explain_p)
6755     inform (input_location,
6756 	    "  template argument %qE does not match "
6757 	    "pointer-to-member constant %qE",
6758 	    arg, parm);
6759   return unify_invalid (explain_p);
6760 }
6761 
6762 static int
unify_expression_unequal(bool explain_p,tree parm,tree arg)6763 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6764 {
6765   if (explain_p)
6766     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6767   return unify_invalid (explain_p);
6768 }
6769 
6770 static int
unify_parameter_pack_inconsistent(bool explain_p,tree old_arg,tree new_arg)6771 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6772 {
6773   if (explain_p)
6774     inform (input_location,
6775 	    "  inconsistent parameter pack deduction with %qT and %qT",
6776 	    old_arg, new_arg);
6777   return unify_invalid (explain_p);
6778 }
6779 
6780 static int
unify_inconsistency(bool explain_p,tree parm,tree first,tree second)6781 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6782 {
6783   if (explain_p)
6784     {
6785       if (TYPE_P (parm))
6786 	inform (input_location,
6787 		"  deduced conflicting types for parameter %qT (%qT and %qT)",
6788 		parm, first, second);
6789       else
6790 	inform (input_location,
6791 		"  deduced conflicting values for non-type parameter "
6792 		"%qE (%qE and %qE)", parm, first, second);
6793     }
6794   return unify_invalid (explain_p);
6795 }
6796 
6797 static int
unify_vla_arg(bool explain_p,tree arg)6798 unify_vla_arg (bool explain_p, tree arg)
6799 {
6800   if (explain_p)
6801     inform (input_location,
6802 	    "  variable-sized array type %qT is not "
6803 	    "a valid template argument",
6804 	    arg);
6805   return unify_invalid (explain_p);
6806 }
6807 
6808 static int
unify_method_type_error(bool explain_p,tree arg)6809 unify_method_type_error (bool explain_p, tree arg)
6810 {
6811   if (explain_p)
6812     inform (input_location,
6813 	    "  member function type %qT is not a valid template argument",
6814 	    arg);
6815   return unify_invalid (explain_p);
6816 }
6817 
6818 static int
6819 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6820 {
6821   if (explain_p)
6822     {
6823       if (least_p)
6824 	inform_n (input_location, wanted,
6825 		  "  candidate expects at least %d argument, %d provided",
6826 		  "  candidate expects at least %d arguments, %d provided",
6827 		  wanted, have);
6828       else
6829 	inform_n (input_location, wanted,
6830 		  "  candidate expects %d argument, %d provided",
6831 		  "  candidate expects %d arguments, %d provided",
6832 		  wanted, have);
6833     }
6834   return unify_invalid (explain_p);
6835 }
6836 
6837 static int
unify_too_many_arguments(bool explain_p,int have,int wanted)6838 unify_too_many_arguments (bool explain_p, int have, int wanted)
6839 {
6840   return unify_arity (explain_p, have, wanted);
6841 }
6842 
6843 static int
6844 unify_too_few_arguments (bool explain_p, int have, int wanted,
6845 			 bool least_p = false)
6846 {
6847   return unify_arity (explain_p, have, wanted, least_p);
6848 }
6849 
6850 static int
unify_arg_conversion(bool explain_p,tree to_type,tree from_type,tree arg)6851 unify_arg_conversion (bool explain_p, tree to_type,
6852 		      tree from_type, tree arg)
6853 {
6854   if (explain_p)
6855     inform (cp_expr_loc_or_input_loc (arg),
6856 	    "  cannot convert %qE (type %qT) to type %qT",
6857 	    arg, from_type, to_type);
6858   return unify_invalid (explain_p);
6859 }
6860 
6861 static int
unify_no_common_base(bool explain_p,enum template_base_result r,tree parm,tree arg)6862 unify_no_common_base (bool explain_p, enum template_base_result r,
6863 		      tree parm, tree arg)
6864 {
6865   if (explain_p)
6866     switch (r)
6867       {
6868       case tbr_ambiguous_baseclass:
6869 	inform (input_location, "  %qT is an ambiguous base class of %qT",
6870 		parm, arg);
6871 	break;
6872       default:
6873 	inform (input_location, "  %qT is not derived from %qT", arg, parm);
6874 	break;
6875       }
6876   return unify_invalid (explain_p);
6877 }
6878 
6879 static int
unify_inconsistent_template_template_parameters(bool explain_p)6880 unify_inconsistent_template_template_parameters (bool explain_p)
6881 {
6882   if (explain_p)
6883     inform (input_location,
6884 	    "  template parameters of a template template argument are "
6885 	    "inconsistent with other deduced template arguments");
6886   return unify_invalid (explain_p);
6887 }
6888 
6889 static int
unify_template_deduction_failure(bool explain_p,tree parm,tree arg)6890 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6891 {
6892   if (explain_p)
6893     inform (input_location,
6894 	    "  cannot deduce a template for %qT from non-template type %qT",
6895 	    parm, arg);
6896   return unify_invalid (explain_p);
6897 }
6898 
6899 static int
unify_template_argument_mismatch(bool explain_p,tree parm,tree arg)6900 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6901 {
6902   if (explain_p)
6903     inform (input_location,
6904 	    "  template argument %qE does not match %qE", arg, parm);
6905   return unify_invalid (explain_p);
6906 }
6907 
6908 /* True if T is a C++20 template parameter object to store the argument for a
6909    template parameter of class type.  */
6910 
6911 bool
template_parm_object_p(const_tree t)6912 template_parm_object_p (const_tree t)
6913 {
6914   return (TREE_CODE (t) == VAR_DECL && DECL_ARTIFICIAL (t) && DECL_NAME (t)
6915 	  && !strncmp (IDENTIFIER_POINTER (DECL_NAME (t)), "_ZTA", 4));
6916 }
6917 
6918 /* Subroutine of convert_nontype_argument, to check whether EXPR, as an
6919    argument for TYPE, points to an unsuitable object.  */
6920 
6921 static bool
invalid_tparm_referent_p(tree type,tree expr,tsubst_flags_t complain)6922 invalid_tparm_referent_p (tree type, tree expr, tsubst_flags_t complain)
6923 {
6924   switch (TREE_CODE (expr))
6925     {
6926     CASE_CONVERT:
6927       return invalid_tparm_referent_p (type, TREE_OPERAND (expr, 0),
6928 				       complain);
6929 
6930     case TARGET_EXPR:
6931       return invalid_tparm_referent_p (type, TARGET_EXPR_INITIAL (expr),
6932 				       complain);
6933 
6934     case CONSTRUCTOR:
6935       {
6936 	unsigned i; tree elt;
6937 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expr), i, elt)
6938 	  if (invalid_tparm_referent_p (TREE_TYPE (elt), elt, complain))
6939 	    return true;
6940       }
6941       break;
6942 
6943     case ADDR_EXPR:
6944       {
6945 	tree decl = TREE_OPERAND (expr, 0);
6946 
6947 	if (!VAR_P (decl))
6948 	  {
6949 	    if (complain & tf_error)
6950 	      error_at (cp_expr_loc_or_input_loc (expr),
6951 			"%qE is not a valid template argument of type %qT "
6952 			"because %qE is not a variable", expr, type, decl);
6953 	    return true;
6954 	  }
6955 	else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6956 	  {
6957 	    if (complain & tf_error)
6958 	      error_at (cp_expr_loc_or_input_loc (expr),
6959 			"%qE is not a valid template argument of type %qT "
6960 			"in C++98 because %qD does not have external linkage",
6961 			expr, type, decl);
6962 	    return true;
6963 	  }
6964 	else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
6965 		 && decl_linkage (decl) == lk_none)
6966 	  {
6967 	    if (complain & tf_error)
6968 	      error_at (cp_expr_loc_or_input_loc (expr),
6969 			"%qE is not a valid template argument of type %qT "
6970 			"because %qD has no linkage", expr, type, decl);
6971 	    return true;
6972 	  }
6973 	/* C++17: For a non-type template-parameter of reference or pointer
6974 	   type, the value of the constant expression shall not refer to (or
6975 	   for a pointer type, shall not be the address of):
6976 	   * a subobject (4.5),
6977 	   * a temporary object (15.2),
6978 	   * a string literal (5.13.5),
6979 	   * the result of a typeid expression (8.2.8), or
6980 	   * a predefined __func__ variable (11.4.1).  */
6981 	else if (DECL_ARTIFICIAL (decl))
6982 	  {
6983 	    if (complain & tf_error)
6984 	      error ("the address of %qD is not a valid template argument",
6985 		     decl);
6986 	    return true;
6987 	  }
6988 	else if (!same_type_ignoring_top_level_qualifiers_p
6989 		 (strip_array_types (TREE_TYPE (type)),
6990 		  strip_array_types (TREE_TYPE (decl))))
6991 	  {
6992 	    if (complain & tf_error)
6993 	      error ("the address of the %qT subobject of %qD is not a "
6994 		     "valid template argument", TREE_TYPE (type), decl);
6995 	    return true;
6996 	  }
6997 	else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
6998 	  {
6999 	    if (complain & tf_error)
7000 	      error ("the address of %qD is not a valid template argument "
7001 		     "because it does not have static storage duration",
7002 		     decl);
7003 	    return true;
7004 	  }
7005       }
7006       break;
7007 
7008     default:
7009       if (!INDIRECT_TYPE_P (type))
7010 	/* We're only concerned about pointers and references here.  */;
7011       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7012 	/* Null pointer values are OK in C++11.  */;
7013       else
7014 	{
7015 	  if (VAR_P (expr))
7016 	    {
7017 	      if (complain & tf_error)
7018 		error ("%qD is not a valid template argument "
7019 		       "because %qD is a variable, not the address of "
7020 		       "a variable", expr, expr);
7021 	      return true;
7022 	    }
7023 	  else
7024 	    {
7025 	      if (complain & tf_error)
7026 		error ("%qE is not a valid template argument for %qT "
7027 		       "because it is not the address of a variable",
7028 		       expr, type);
7029 	      return true;
7030 	    }
7031 	}
7032     }
7033   return false;
7034 
7035 }
7036 
7037 /* The template arguments corresponding to template parameter objects of types
7038    that contain pointers to members.  */
7039 
7040 static GTY(()) hash_map<tree, tree> *tparm_obj_values;
7041 
7042 /* Return a VAR_DECL for the C++20 template parameter object corresponding to
7043    template argument EXPR.  */
7044 
7045 static tree
get_template_parm_object(tree expr,tsubst_flags_t complain)7046 get_template_parm_object (tree expr, tsubst_flags_t complain)
7047 {
7048   if (TREE_CODE (expr) == TARGET_EXPR)
7049     expr = TARGET_EXPR_INITIAL (expr);
7050 
7051   if (!TREE_CONSTANT (expr))
7052     {
7053       if ((complain & tf_error)
7054 	  && require_rvalue_constant_expression (expr))
7055 	cxx_constant_value (expr);
7056       return error_mark_node;
7057     }
7058   if (invalid_tparm_referent_p (TREE_TYPE (expr), expr, complain))
7059     return error_mark_node;
7060 
7061   tree name = mangle_template_parm_object (expr);
7062   tree decl = get_global_binding (name);
7063   if (decl)
7064     return decl;
7065 
7066   tree type = cp_build_qualified_type (TREE_TYPE (expr), TYPE_QUAL_CONST);
7067   decl = create_temporary_var (type);
7068   TREE_STATIC (decl) = true;
7069   DECL_DECLARED_CONSTEXPR_P (decl) = true;
7070   TREE_READONLY (decl) = true;
7071   DECL_NAME (decl) = name;
7072   SET_DECL_ASSEMBLER_NAME (decl, name);
7073   DECL_CONTEXT (decl) = global_namespace;
7074   comdat_linkage (decl);
7075 
7076   if (!zero_init_p (type))
7077     {
7078       /* If EXPR contains any PTRMEM_CST, they will get clobbered by
7079 	 lower_var_init before we're done mangling.  So store the original
7080 	 value elsewhere.  */
7081       tree copy = unshare_constructor (expr);
7082       hash_map_safe_put<hm_ggc> (tparm_obj_values, decl, copy);
7083     }
7084 
7085   pushdecl_top_level_and_finish (decl, expr);
7086 
7087   return decl;
7088 }
7089 
7090 /* Return the actual template argument corresponding to template parameter
7091    object VAR.  */
7092 
7093 tree
tparm_object_argument(tree var)7094 tparm_object_argument (tree var)
7095 {
7096   if (zero_init_p (TREE_TYPE (var)))
7097     return DECL_INITIAL (var);
7098   return *(tparm_obj_values->get (var));
7099 }
7100 
7101 /* Attempt to convert the non-type template parameter EXPR to the
7102    indicated TYPE.  If the conversion is successful, return the
7103    converted value.  If the conversion is unsuccessful, return
7104    NULL_TREE if we issued an error message, or error_mark_node if we
7105    did not.  We issue error messages for out-and-out bad template
7106    parameters, but not simply because the conversion failed, since we
7107    might be just trying to do argument deduction.  Both TYPE and EXPR
7108    must be non-dependent.
7109 
7110    The conversion follows the special rules described in
7111    [temp.arg.nontype], and it is much more strict than an implicit
7112    conversion.
7113 
7114    This function is called twice for each template argument (see
7115    lookup_template_class for a more accurate description of this
7116    problem). This means that we need to handle expressions which
7117    are not valid in a C++ source, but can be created from the
7118    first call (for instance, casts to perform conversions). These
7119    hacks can go away after we fix the double coercion problem.  */
7120 
7121 static tree
convert_nontype_argument(tree type,tree expr,tsubst_flags_t complain)7122 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
7123 {
7124   tree expr_type;
7125   location_t loc = cp_expr_loc_or_input_loc (expr);
7126 
7127   /* Detect immediately string literals as invalid non-type argument.
7128      This special-case is not needed for correctness (we would easily
7129      catch this later), but only to provide better diagnostic for this
7130      common user mistake. As suggested by DR 100, we do not mention
7131      linkage issues in the diagnostic as this is not the point.  */
7132   if (TREE_CODE (expr) == STRING_CST && !CLASS_TYPE_P (type))
7133     {
7134       if (complain & tf_error)
7135 	error ("%qE is not a valid template argument for type %qT "
7136 	       "because string literals can never be used in this context",
7137 	       expr, type);
7138       return NULL_TREE;
7139     }
7140 
7141   /* Add the ADDR_EXPR now for the benefit of
7142      value_dependent_expression_p.  */
7143   if (TYPE_PTROBV_P (type)
7144       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
7145     {
7146       expr = decay_conversion (expr, complain);
7147       if (expr == error_mark_node)
7148 	return error_mark_node;
7149     }
7150 
7151   /* If we are in a template, EXPR may be non-dependent, but still
7152      have a syntactic, rather than semantic, form.  For example, EXPR
7153      might be a SCOPE_REF, rather than the VAR_DECL to which the
7154      SCOPE_REF refers.  Preserving the qualifying scope is necessary
7155      so that access checking can be performed when the template is
7156      instantiated -- but here we need the resolved form so that we can
7157      convert the argument.  */
7158   bool non_dep = false;
7159   if (TYPE_REF_OBJ_P (type)
7160       && has_value_dependent_address (expr))
7161     /* If we want the address and it's value-dependent, don't fold.  */;
7162   else if (processing_template_decl
7163 	   && is_nondependent_constant_expression (expr))
7164     non_dep = true;
7165   if (error_operand_p (expr))
7166     return error_mark_node;
7167   expr_type = TREE_TYPE (expr);
7168 
7169   /* If the argument is non-dependent, perform any conversions in
7170      non-dependent context as well.  */
7171   processing_template_decl_sentinel s (non_dep);
7172   if (non_dep)
7173     expr = instantiate_non_dependent_expr_internal (expr, complain);
7174 
7175   const bool val_dep_p = value_dependent_expression_p (expr);
7176   if (val_dep_p)
7177     expr = canonicalize_expr_argument (expr, complain);
7178 
7179   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
7180      to a non-type argument of "nullptr".  */
7181   if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
7182     expr = fold_simple (convert (type, expr));
7183 
7184   /* In C++11, integral or enumeration non-type template arguments can be
7185      arbitrary constant expressions.  Pointer and pointer to
7186      member arguments can be general constant expressions that evaluate
7187      to a null value, but otherwise still need to be of a specific form.  */
7188   if (cxx_dialect >= cxx11)
7189     {
7190       if (TREE_CODE (expr) == PTRMEM_CST && TYPE_PTRMEM_P (type))
7191 	/* A PTRMEM_CST is already constant, and a valid template
7192 	   argument for a parameter of pointer to member type, we just want
7193 	   to leave it in that form rather than lower it to a
7194 	   CONSTRUCTOR.  */;
7195       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
7196 	       || cxx_dialect >= cxx17)
7197 	{
7198 	  /* C++17: A template-argument for a non-type template-parameter shall
7199 	     be a converted constant expression (8.20) of the type of the
7200 	     template-parameter.  */
7201 	  expr = build_converted_constant_expr (type, expr, complain);
7202 	  if (expr == error_mark_node)
7203 	    /* Make sure we return NULL_TREE only if we have really issued
7204 	       an error, as described above.  */
7205 	    return (complain & tf_error) ? NULL_TREE : error_mark_node;
7206 	  else if (TREE_CODE (expr) == IMPLICIT_CONV_EXPR)
7207 	    {
7208 	      IMPLICIT_CONV_EXPR_NONTYPE_ARG (expr) = true;
7209 	      return expr;
7210 	    }
7211 	  expr = maybe_constant_value (expr, NULL_TREE,
7212 				       /*manifestly_const_eval=*/true);
7213 	  expr = convert_from_reference (expr);
7214 	}
7215       else if (TYPE_PTR_OR_PTRMEM_P (type))
7216 	{
7217 	  tree folded = maybe_constant_value (expr, NULL_TREE,
7218 					      /*manifestly_const_eval=*/true);
7219 	  if (TYPE_PTR_P (type) ? integer_zerop (folded)
7220 	      : null_member_pointer_value_p (folded))
7221 	    expr = folded;
7222 	}
7223     }
7224 
7225   if (TYPE_REF_P (type))
7226     expr = mark_lvalue_use (expr);
7227   else
7228     expr = mark_rvalue_use (expr);
7229 
7230   /* HACK: Due to double coercion, we can get a
7231      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
7232      which is the tree that we built on the first call (see
7233      below when coercing to reference to object or to reference to
7234      function). We just strip everything and get to the arg.
7235      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
7236      for examples.  */
7237   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
7238     {
7239       tree probe_type, probe = expr;
7240       if (REFERENCE_REF_P (probe))
7241 	probe = TREE_OPERAND (probe, 0);
7242       probe_type = TREE_TYPE (probe);
7243       if (TREE_CODE (probe) == NOP_EXPR)
7244 	{
7245 	  /* ??? Maybe we could use convert_from_reference here, but we
7246 	     would need to relax its constraints because the NOP_EXPR
7247 	     could actually change the type to something more cv-qualified,
7248 	     and this is not folded by convert_from_reference.  */
7249 	  tree addr = TREE_OPERAND (probe, 0);
7250 	  if (TYPE_REF_P (probe_type)
7251 	      && TREE_CODE (addr) == ADDR_EXPR
7252 	      && TYPE_PTR_P (TREE_TYPE (addr))
7253 	      && (same_type_ignoring_top_level_qualifiers_p
7254 		  (TREE_TYPE (probe_type),
7255 		   TREE_TYPE (TREE_TYPE (addr)))))
7256 	    {
7257 	      expr = TREE_OPERAND (addr, 0);
7258 	      expr_type = TREE_TYPE (probe_type);
7259 	    }
7260 	}
7261     }
7262 
7263   /* [temp.arg.nontype]/5, bullet 1
7264 
7265      For a non-type template-parameter of integral or enumeration type,
7266      integral promotions (_conv.prom_) and integral conversions
7267      (_conv.integral_) are applied.  */
7268   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
7269     {
7270       if (cxx_dialect < cxx11)
7271 	{
7272 	  tree t = build_converted_constant_expr (type, expr, complain);
7273 	  t = maybe_constant_value (t);
7274 	  if (t != error_mark_node)
7275 	    expr = t;
7276 	}
7277 
7278       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
7279 	return error_mark_node;
7280 
7281       /* Notice that there are constant expressions like '4 % 0' which
7282 	 do not fold into integer constants.  */
7283       if (TREE_CODE (expr) != INTEGER_CST && !val_dep_p)
7284 	{
7285 	  if (complain & tf_error)
7286 	    {
7287 	      int errs = errorcount, warns = warningcount + werrorcount;
7288 	      if (!require_potential_constant_expression (expr))
7289 		expr = error_mark_node;
7290 	      else
7291 		expr = cxx_constant_value (expr);
7292 	      if (errorcount > errs || warningcount + werrorcount > warns)
7293 		inform (loc, "in template argument for type %qT", type);
7294 	      if (expr == error_mark_node)
7295 		return NULL_TREE;
7296 	      /* else cxx_constant_value complained but gave us
7297 		 a real constant, so go ahead.  */
7298 	      if (TREE_CODE (expr) != INTEGER_CST)
7299 		{
7300 		  /* Some assemble time constant expressions like
7301 		     (intptr_t)&&lab1 - (intptr_t)&&lab2 or
7302 		     4 + (intptr_t)&&var satisfy reduced_constant_expression_p
7303 		     as we can emit them into .rodata initializers of
7304 		     variables, yet they can't fold into an INTEGER_CST at
7305 		     compile time.  Refuse them here.  */
7306 		  gcc_checking_assert (reduced_constant_expression_p (expr));
7307 		  error_at (loc, "template argument %qE for type %qT not "
7308 				 "a constant integer", expr, type);
7309 		  return NULL_TREE;
7310 		}
7311 	    }
7312 	  else
7313 	    return NULL_TREE;
7314 	}
7315 
7316       /* Avoid typedef problems.  */
7317       if (TREE_TYPE (expr) != type)
7318 	expr = fold_convert (type, expr);
7319     }
7320   /* [temp.arg.nontype]/5, bullet 2
7321 
7322      For a non-type template-parameter of type pointer to object,
7323      qualification conversions (_conv.qual_) and the array-to-pointer
7324      conversion (_conv.array_) are applied.  */
7325   else if (TYPE_PTROBV_P (type))
7326     {
7327       tree decayed = expr;
7328 
7329       /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
7330 	 decay_conversion or an explicit cast.  If it's a problematic cast,
7331 	 we'll complain about it below.  */
7332       if (TREE_CODE (expr) == NOP_EXPR)
7333 	{
7334 	  tree probe = expr;
7335 	  STRIP_NOPS (probe);
7336 	  if (TREE_CODE (probe) == ADDR_EXPR
7337 	      && TYPE_PTR_P (TREE_TYPE (probe)))
7338 	    {
7339 	      expr = probe;
7340 	      expr_type = TREE_TYPE (expr);
7341 	    }
7342 	}
7343 
7344       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
7345 
7346 	 A template-argument for a non-type, non-template template-parameter
7347 	 shall be one of: [...]
7348 
7349 	 -- the name of a non-type template-parameter;
7350 	 -- the address of an object or function with external linkage, [...]
7351 	    expressed as "& id-expression" where the & is optional if the name
7352 	    refers to a function or array, or if the corresponding
7353 	    template-parameter is a reference.
7354 
7355 	Here, we do not care about functions, as they are invalid anyway
7356 	for a parameter of type pointer-to-object.  */
7357 
7358       if (val_dep_p)
7359 	/* Non-type template parameters are OK.  */
7360 	;
7361       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
7362 	/* Null pointer values are OK in C++11.  */;
7363       else if (TREE_CODE (expr) != ADDR_EXPR
7364 	       && !INDIRECT_TYPE_P (expr_type))
7365 	/* Other values, like integer constants, might be valid
7366 	   non-type arguments of some other type.  */
7367 	return error_mark_node;
7368       else if (invalid_tparm_referent_p (type, expr, complain))
7369 	return NULL_TREE;
7370 
7371       expr = decayed;
7372 
7373       expr = perform_qualification_conversions (type, expr);
7374       if (expr == error_mark_node)
7375 	return error_mark_node;
7376     }
7377   /* [temp.arg.nontype]/5, bullet 3
7378 
7379      For a non-type template-parameter of type reference to object, no
7380      conversions apply. The type referred to by the reference may be more
7381      cv-qualified than the (otherwise identical) type of the
7382      template-argument. The template-parameter is bound directly to the
7383      template-argument, which must be an lvalue.  */
7384   else if (TYPE_REF_OBJ_P (type))
7385     {
7386       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
7387 						      expr_type))
7388 	return error_mark_node;
7389 
7390       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
7391 	{
7392 	  if (complain & tf_error)
7393 	    error ("%qE is not a valid template argument for type %qT "
7394 		   "because of conflicts in cv-qualification", expr, type);
7395 	  return NULL_TREE;
7396 	}
7397 
7398       if (!lvalue_p (expr))
7399 	{
7400 	  if (complain & tf_error)
7401 	    error ("%qE is not a valid template argument for type %qT "
7402 		   "because it is not an lvalue", expr, type);
7403 	  return NULL_TREE;
7404 	}
7405 
7406       /* [temp.arg.nontype]/1
7407 
7408 	 A template-argument for a non-type, non-template template-parameter
7409 	 shall be one of: [...]
7410 
7411 	 -- the address of an object or function with external linkage.  */
7412       if (INDIRECT_REF_P (expr)
7413 	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
7414 	{
7415 	  expr = TREE_OPERAND (expr, 0);
7416 	  if (DECL_P (expr))
7417 	    {
7418 	      if (complain & tf_error)
7419 		error ("%q#D is not a valid template argument for type %qT "
7420 		       "because a reference variable does not have a constant "
7421 		       "address", expr, type);
7422 	      return NULL_TREE;
7423 	    }
7424 	}
7425 
7426       if (TYPE_REF_OBJ_P (TREE_TYPE (expr)) && val_dep_p)
7427 	/* OK, dependent reference.  We don't want to ask whether a DECL is
7428 	   itself value-dependent, since what we want here is its address.  */;
7429       else
7430 	{
7431 	  expr = build_address (expr);
7432 
7433 	  if (invalid_tparm_referent_p (type, expr, complain))
7434 	    return NULL_TREE;
7435 	}
7436 
7437       if (!same_type_p (type, TREE_TYPE (expr)))
7438 	expr = build_nop (type, expr);
7439     }
7440   /* [temp.arg.nontype]/5, bullet 4
7441 
7442      For a non-type template-parameter of type pointer to function, only
7443      the function-to-pointer conversion (_conv.func_) is applied. If the
7444      template-argument represents a set of overloaded functions (or a
7445      pointer to such), the matching function is selected from the set
7446      (_over.over_).  */
7447   else if (TYPE_PTRFN_P (type))
7448     {
7449       /* If the argument is a template-id, we might not have enough
7450 	 context information to decay the pointer.  */
7451       if (!type_unknown_p (expr_type))
7452 	{
7453 	  expr = decay_conversion (expr, complain);
7454 	  if (expr == error_mark_node)
7455 	    return error_mark_node;
7456 	}
7457 
7458       if (cxx_dialect >= cxx11 && integer_zerop (expr))
7459 	/* Null pointer values are OK in C++11.  */
7460 	return perform_qualification_conversions (type, expr);
7461 
7462       expr = convert_nontype_argument_function (type, expr, complain);
7463       if (!expr || expr == error_mark_node)
7464 	return expr;
7465     }
7466   /* [temp.arg.nontype]/5, bullet 5
7467 
7468      For a non-type template-parameter of type reference to function, no
7469      conversions apply. If the template-argument represents a set of
7470      overloaded functions, the matching function is selected from the set
7471      (_over.over_).  */
7472   else if (TYPE_REFFN_P (type))
7473     {
7474       if (TREE_CODE (expr) == ADDR_EXPR)
7475 	{
7476 	  if (complain & tf_error)
7477 	    {
7478 	      error ("%qE is not a valid template argument for type %qT "
7479 		     "because it is a pointer", expr, type);
7480 	      inform (input_location, "try using %qE instead",
7481 		      TREE_OPERAND (expr, 0));
7482 	    }
7483 	  return NULL_TREE;
7484 	}
7485 
7486       expr = convert_nontype_argument_function (type, expr, complain);
7487       if (!expr || expr == error_mark_node)
7488 	return expr;
7489     }
7490   /* [temp.arg.nontype]/5, bullet 6
7491 
7492      For a non-type template-parameter of type pointer to member function,
7493      no conversions apply. If the template-argument represents a set of
7494      overloaded member functions, the matching member function is selected
7495      from the set (_over.over_).  */
7496   else if (TYPE_PTRMEMFUNC_P (type))
7497     {
7498       expr = instantiate_type (type, expr, tf_none);
7499       if (expr == error_mark_node)
7500 	return error_mark_node;
7501 
7502       /* [temp.arg.nontype] bullet 1 says the pointer to member
7503          expression must be a pointer-to-member constant.  */
7504       if (!val_dep_p
7505 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7506 	return NULL_TREE;
7507 
7508       /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7509 	 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead.  */
7510       if (fnptr_conv_p (type, TREE_TYPE (expr)))
7511 	expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7512     }
7513   /* [temp.arg.nontype]/5, bullet 7
7514 
7515      For a non-type template-parameter of type pointer to data member,
7516      qualification conversions (_conv.qual_) are applied.  */
7517   else if (TYPE_PTRDATAMEM_P (type))
7518     {
7519       /* [temp.arg.nontype] bullet 1 says the pointer to member
7520          expression must be a pointer-to-member constant.  */
7521       if (!val_dep_p
7522 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7523 	return NULL_TREE;
7524 
7525       expr = perform_qualification_conversions (type, expr);
7526       if (expr == error_mark_node)
7527 	return expr;
7528     }
7529   else if (NULLPTR_TYPE_P (type))
7530     {
7531       if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7532 	{
7533 	  if (complain & tf_error)
7534 	    error ("%qE is not a valid template argument for type %qT "
7535 		   "because it is of type %qT", expr, type, TREE_TYPE (expr));
7536 	  return NULL_TREE;
7537 	}
7538       return expr;
7539     }
7540   else if (CLASS_TYPE_P (type))
7541     {
7542       /* Replace the argument with a reference to the corresponding template
7543 	 parameter object.  */
7544       if (!val_dep_p)
7545 	expr = get_template_parm_object (expr, complain);
7546       if (expr == error_mark_node)
7547 	return NULL_TREE;
7548     }
7549   /* A template non-type parameter must be one of the above.  */
7550   else
7551     gcc_unreachable ();
7552 
7553   /* Sanity check: did we actually convert the argument to the
7554      right type?  */
7555   gcc_assert (same_type_ignoring_top_level_qualifiers_p
7556 	      (type, TREE_TYPE (expr)));
7557   return convert_from_reference (expr);
7558 }
7559 
7560 /* Subroutine of coerce_template_template_parms, which returns 1 if
7561    PARM_PARM and ARG_PARM match using the rule for the template
7562    parameters of template template parameters. Both PARM and ARG are
7563    template parameters; the rest of the arguments are the same as for
7564    coerce_template_template_parms.
7565  */
7566 static int
coerce_template_template_parm(tree parm,tree arg,tsubst_flags_t complain,tree in_decl,tree outer_args)7567 coerce_template_template_parm (tree parm,
7568                               tree arg,
7569                               tsubst_flags_t complain,
7570                               tree in_decl,
7571                               tree outer_args)
7572 {
7573   if (arg == NULL_TREE || error_operand_p (arg)
7574       || parm == NULL_TREE || error_operand_p (parm))
7575     return 0;
7576 
7577   if (TREE_CODE (arg) != TREE_CODE (parm))
7578     return 0;
7579 
7580   switch (TREE_CODE (parm))
7581     {
7582     case TEMPLATE_DECL:
7583       /* We encounter instantiations of templates like
7584 	 template <template <template <class> class> class TT>
7585 	 class C;  */
7586       {
7587 	tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7588 	tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7589 
7590 	if (!coerce_template_template_parms
7591 	    (parmparm, argparm, complain, in_decl, outer_args))
7592 	  return 0;
7593       }
7594       /* Fall through.  */
7595 
7596     case TYPE_DECL:
7597       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7598 	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7599 	/* Argument is a parameter pack but parameter is not.  */
7600 	return 0;
7601       break;
7602 
7603     case PARM_DECL:
7604       /* The tsubst call is used to handle cases such as
7605 
7606            template <int> class C {};
7607 	   template <class T, template <T> class TT> class D {};
7608 	   D<int, C> d;
7609 
7610 	 i.e. the parameter list of TT depends on earlier parameters.  */
7611       if (!uses_template_parms (TREE_TYPE (arg)))
7612 	{
7613 	  tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7614 	  if (!uses_template_parms (t)
7615 	      && !same_type_p (t, TREE_TYPE (arg)))
7616 	    return 0;
7617 	}
7618 
7619       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7620 	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7621 	/* Argument is a parameter pack but parameter is not.  */
7622 	return 0;
7623 
7624       break;
7625 
7626     default:
7627       gcc_unreachable ();
7628     }
7629 
7630   return 1;
7631 }
7632 
7633 /* Coerce template argument list ARGLIST for use with template
7634    template-parameter TEMPL.  */
7635 
7636 static tree
coerce_template_args_for_ttp(tree templ,tree arglist,tsubst_flags_t complain)7637 coerce_template_args_for_ttp (tree templ, tree arglist,
7638 			      tsubst_flags_t complain)
7639 {
7640   /* Consider an example where a template template parameter declared as
7641 
7642      template <class T, class U = std::allocator<T> > class TT
7643 
7644      The template parameter level of T and U are one level larger than
7645      of TT.  To proper process the default argument of U, say when an
7646      instantiation `TT<int>' is seen, we need to build the full
7647      arguments containing {int} as the innermost level.  Outer levels,
7648      available when not appearing as default template argument, can be
7649      obtained from the arguments of the enclosing template.
7650 
7651      Suppose that TT is later substituted with std::vector.  The above
7652      instantiation is `TT<int, std::allocator<T> >' with TT at
7653      level 1, and T at level 2, while the template arguments at level 1
7654      becomes {std::vector} and the inner level 2 is {int}.  */
7655 
7656   tree outer = DECL_CONTEXT (templ);
7657   if (outer)
7658     outer = generic_targs_for (outer);
7659   else if (current_template_parms)
7660     {
7661       /* This is an argument of the current template, so we haven't set
7662 	 DECL_CONTEXT yet.  */
7663       tree relevant_template_parms;
7664 
7665       /* Parameter levels that are greater than the level of the given
7666 	 template template parm are irrelevant.  */
7667       relevant_template_parms = current_template_parms;
7668       while (TMPL_PARMS_DEPTH (relevant_template_parms)
7669 	     != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7670 	relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7671 
7672       outer = template_parms_to_args (relevant_template_parms);
7673     }
7674 
7675   if (outer)
7676     arglist = add_to_template_args (outer, arglist);
7677 
7678   tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7679   return coerce_template_parms (parmlist, arglist, templ,
7680 				complain,
7681 				/*require_all_args=*/true,
7682 				/*use_default_args=*/true);
7683 }
7684 
7685 /* A cache of template template parameters with match-all default
7686    arguments.  */
7687 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7688 
7689 /* T is a bound template template-parameter.  Copy its arguments into default
7690    arguments of the template template-parameter's template parameters.  */
7691 
7692 static tree
add_defaults_to_ttp(tree otmpl)7693 add_defaults_to_ttp (tree otmpl)
7694 {
7695   if (tree *c = hash_map_safe_get (defaulted_ttp_cache, otmpl))
7696     return *c;
7697 
7698   tree ntmpl = copy_node (otmpl);
7699 
7700   tree ntype = copy_node (TREE_TYPE (otmpl));
7701   TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7702   TYPE_MAIN_VARIANT (ntype) = ntype;
7703   TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7704   TYPE_NAME (ntype) = ntmpl;
7705   SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7706 
7707   tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7708     = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7709   TEMPLATE_PARM_DECL (idx) = ntmpl;
7710   TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7711 
7712   tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7713   tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7714   TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7715   tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7716   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7717     {
7718       tree o = TREE_VEC_ELT (vec, i);
7719       if (!template_parameter_pack_p (TREE_VALUE (o)))
7720 	{
7721 	  tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7722 	  TREE_PURPOSE (n) = any_targ_node;
7723 	}
7724     }
7725 
7726   hash_map_safe_put<hm_ggc> (defaulted_ttp_cache, otmpl, ntmpl);
7727   return ntmpl;
7728 }
7729 
7730 /* ARG is a bound potential template template-argument, and PARGS is a list
7731    of arguments for the corresponding template template-parameter.  Adjust
7732    PARGS as appropriate for application to ARG's template, and if ARG is a
7733    BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7734    arguments to the template template parameter.  */
7735 
7736 static tree
coerce_ttp_args_for_tta(tree & arg,tree pargs,tsubst_flags_t complain)7737 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7738 {
7739   ++processing_template_decl;
7740   tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7741   if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7742     {
7743       /* When comparing two template template-parameters in partial ordering,
7744 	 rewrite the one currently being used as an argument to have default
7745 	 arguments for all parameters.  */
7746       arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7747       pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7748       if (pargs != error_mark_node)
7749 	arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7750 					   TYPE_TI_ARGS (arg));
7751     }
7752   else
7753     {
7754       tree aparms
7755 	= INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7756       pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7757 				       /*require_all*/true,
7758 				       /*use_default*/true);
7759     }
7760   --processing_template_decl;
7761   return pargs;
7762 }
7763 
7764 /* Subroutine of unify for the case when PARM is a
7765    BOUND_TEMPLATE_TEMPLATE_PARM.  */
7766 
7767 static int
unify_bound_ttp_args(tree tparms,tree targs,tree parm,tree & arg,bool explain_p)7768 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7769 		      bool explain_p)
7770 {
7771   tree parmvec = TYPE_TI_ARGS (parm);
7772   tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7773 
7774   /* The template template parm might be variadic and the argument
7775      not, so flatten both argument lists.  */
7776   parmvec = expand_template_argument_pack (parmvec);
7777   argvec = expand_template_argument_pack (argvec);
7778 
7779   if (flag_new_ttp)
7780     {
7781       /* In keeping with P0522R0, adjust P's template arguments
7782 	 to apply to A's template; then flatten it again.  */
7783       tree nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7784       nparmvec = expand_template_argument_pack (nparmvec);
7785 
7786       if (unify (tparms, targs, nparmvec, argvec,
7787 		 UNIFY_ALLOW_NONE, explain_p))
7788 	return 1;
7789 
7790       /* If the P0522 adjustment eliminated a pack expansion, deduce
7791 	 empty packs.  */
7792       if (flag_new_ttp
7793 	  && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7794 	  && unify_pack_expansion (tparms, targs, parmvec, argvec,
7795 				   DEDUCE_EXACT, /*sub*/true, explain_p))
7796 	return 1;
7797     }
7798   else
7799     {
7800       /* Deduce arguments T, i from TT<T> or TT<i>.
7801 	 We check each element of PARMVEC and ARGVEC individually
7802 	 rather than the whole TREE_VEC since they can have
7803 	 different number of elements, which is allowed under N2555.  */
7804 
7805       int len = TREE_VEC_LENGTH (parmvec);
7806 
7807       /* Check if the parameters end in a pack, making them
7808 	 variadic.  */
7809       int parm_variadic_p = 0;
7810       if (len > 0
7811 	  && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7812 	parm_variadic_p = 1;
7813 
7814       for (int i = 0; i < len - parm_variadic_p; ++i)
7815 	/* If the template argument list of P contains a pack
7816 	   expansion that is not the last template argument, the
7817 	   entire template argument list is a non-deduced
7818 	   context.  */
7819 	if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7820 	  return unify_success (explain_p);
7821 
7822       if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7823 	return unify_too_few_arguments (explain_p,
7824 					TREE_VEC_LENGTH (argvec), len);
7825 
7826       for (int i = 0; i < len - parm_variadic_p; ++i)
7827 	if (unify (tparms, targs,
7828 		   TREE_VEC_ELT (parmvec, i),
7829 		   TREE_VEC_ELT (argvec, i),
7830 		   UNIFY_ALLOW_NONE, explain_p))
7831 	  return 1;
7832 
7833       if (parm_variadic_p
7834 	  && unify_pack_expansion (tparms, targs,
7835 				   parmvec, argvec,
7836 				   DEDUCE_EXACT,
7837 				   /*subr=*/true, explain_p))
7838 	return 1;
7839     }
7840 
7841   return 0;
7842 }
7843 
7844 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
7845    template template parameters.  Both PARM_PARMS and ARG_PARMS are
7846    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
7847    or PARM_DECL.
7848 
7849    Consider the example:
7850      template <class T> class A;
7851      template<template <class U> class TT> class B;
7852 
7853    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
7854    the parameters to A, and OUTER_ARGS contains A.  */
7855 
7856 static int
coerce_template_template_parms(tree parm_parms,tree arg_parms,tsubst_flags_t complain,tree in_decl,tree outer_args)7857 coerce_template_template_parms (tree parm_parms,
7858 				tree arg_parms,
7859 				tsubst_flags_t complain,
7860 				tree in_decl,
7861 				tree outer_args)
7862 {
7863   int nparms, nargs, i;
7864   tree parm, arg;
7865   int variadic_p = 0;
7866 
7867   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
7868   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
7869 
7870   nparms = TREE_VEC_LENGTH (parm_parms);
7871   nargs = TREE_VEC_LENGTH (arg_parms);
7872 
7873   if (flag_new_ttp)
7874     {
7875       /* P0522R0: A template template-parameter P is at least as specialized as
7876 	 a template template-argument A if, given the following rewrite to two
7877 	 function templates, the function template corresponding to P is at
7878 	 least as specialized as the function template corresponding to A
7879 	 according to the partial ordering rules for function templates
7880 	 ([temp.func.order]). Given an invented class template X with the
7881 	 template parameter list of A (including default arguments):
7882 
7883 	 * Each of the two function templates has the same template parameters,
7884 	 respectively, as P or A.
7885 
7886 	 * Each function template has a single function parameter whose type is
7887 	 a specialization of X with template arguments corresponding to the
7888 	 template parameters from the respective function template where, for
7889 	 each template parameter PP in the template parameter list of the
7890 	 function template, a corresponding template argument AA is formed. If
7891 	 PP declares a parameter pack, then AA is the pack expansion
7892 	 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
7893 
7894 	 If the rewrite produces an invalid type, then P is not at least as
7895 	 specialized as A.  */
7896 
7897       /* So coerce P's args to apply to A's parms, and then deduce between A's
7898 	 args and the converted args.  If that succeeds, A is at least as
7899 	 specialized as P, so they match.*/
7900       tree pargs = template_parms_level_to_args (parm_parms);
7901       pargs = add_outermost_template_args (outer_args, pargs);
7902       ++processing_template_decl;
7903       pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
7904 				     /*require_all*/true, /*use_default*/true);
7905       --processing_template_decl;
7906       if (pargs != error_mark_node)
7907 	{
7908 	  tree targs = make_tree_vec (nargs);
7909 	  tree aargs = template_parms_level_to_args (arg_parms);
7910 	  if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
7911 		      /*explain*/false))
7912 	    return 1;
7913 	}
7914     }
7915 
7916   /* Determine whether we have a parameter pack at the end of the
7917      template template parameter's template parameter list.  */
7918   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
7919     {
7920       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
7921 
7922       if (error_operand_p (parm))
7923 	return 0;
7924 
7925       switch (TREE_CODE (parm))
7926         {
7927         case TEMPLATE_DECL:
7928         case TYPE_DECL:
7929           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7930             variadic_p = 1;
7931           break;
7932 
7933         case PARM_DECL:
7934           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7935             variadic_p = 1;
7936           break;
7937 
7938         default:
7939           gcc_unreachable ();
7940         }
7941     }
7942 
7943   if (nargs != nparms
7944       && !(variadic_p && nargs >= nparms - 1))
7945     return 0;
7946 
7947   /* Check all of the template parameters except the parameter pack at
7948      the end (if any).  */
7949   for (i = 0; i < nparms - variadic_p; ++i)
7950     {
7951       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
7952           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7953         continue;
7954 
7955       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7956       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7957 
7958       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7959                                           outer_args))
7960 	return 0;
7961 
7962     }
7963 
7964   if (variadic_p)
7965     {
7966       /* Check each of the template parameters in the template
7967 	 argument against the template parameter pack at the end of
7968 	 the template template parameter.  */
7969       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
7970 	return 0;
7971 
7972       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7973 
7974       for (; i < nargs; ++i)
7975         {
7976           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7977             continue;
7978 
7979           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7980 
7981           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7982                                               outer_args))
7983             return 0;
7984         }
7985     }
7986 
7987   return 1;
7988 }
7989 
7990 /* Verifies that the deduced template arguments (in TARGS) for the
7991    template template parameters (in TPARMS) represent valid bindings,
7992    by comparing the template parameter list of each template argument
7993    to the template parameter list of its corresponding template
7994    template parameter, in accordance with DR150. This
7995    routine can only be called after all template arguments have been
7996    deduced. It will return TRUE if all of the template template
7997    parameter bindings are okay, FALSE otherwise.  */
7998 bool
template_template_parm_bindings_ok_p(tree tparms,tree targs)7999 template_template_parm_bindings_ok_p (tree tparms, tree targs)
8000 {
8001   int i, ntparms = TREE_VEC_LENGTH (tparms);
8002   bool ret = true;
8003 
8004   /* We're dealing with template parms in this process.  */
8005   ++processing_template_decl;
8006 
8007   targs = INNERMOST_TEMPLATE_ARGS (targs);
8008 
8009   for (i = 0; i < ntparms; ++i)
8010     {
8011       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8012       tree targ = TREE_VEC_ELT (targs, i);
8013 
8014       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
8015 	{
8016 	  tree packed_args = NULL_TREE;
8017 	  int idx, len = 1;
8018 
8019 	  if (ARGUMENT_PACK_P (targ))
8020 	    {
8021 	      /* Look inside the argument pack.  */
8022 	      packed_args = ARGUMENT_PACK_ARGS (targ);
8023 	      len = TREE_VEC_LENGTH (packed_args);
8024 	    }
8025 
8026 	  for (idx = 0; idx < len; ++idx)
8027 	    {
8028 	      tree targ_parms = NULL_TREE;
8029 
8030 	      if (packed_args)
8031 		/* Extract the next argument from the argument
8032 		   pack.  */
8033 		targ = TREE_VEC_ELT (packed_args, idx);
8034 
8035 	      if (PACK_EXPANSION_P (targ))
8036 		/* Look at the pattern of the pack expansion.  */
8037 		targ = PACK_EXPANSION_PATTERN (targ);
8038 
8039 	      /* Extract the template parameters from the template
8040 		 argument.  */
8041 	      if (TREE_CODE (targ) == TEMPLATE_DECL)
8042 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
8043 	      else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
8044 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
8045 
8046 	      /* Verify that we can coerce the template template
8047 		 parameters from the template argument to the template
8048 		 parameter.  This requires an exact match.  */
8049 	      if (targ_parms
8050 		  && !coerce_template_template_parms
8051 		       (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
8052 			targ_parms,
8053 			tf_none,
8054 			tparm,
8055 			targs))
8056 		{
8057 		  ret = false;
8058 		  goto out;
8059 		}
8060 	    }
8061 	}
8062     }
8063 
8064  out:
8065 
8066   --processing_template_decl;
8067   return ret;
8068 }
8069 
8070 /* Since type attributes aren't mangled, we need to strip them from
8071    template type arguments.  */
8072 
8073 tree
canonicalize_type_argument(tree arg,tsubst_flags_t complain)8074 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
8075 {
8076   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
8077     return arg;
8078   bool removed_attributes = false;
8079   tree canon = strip_typedefs (arg, &removed_attributes);
8080   if (removed_attributes
8081       && (complain & tf_warning))
8082     warning (OPT_Wignored_attributes,
8083 	     "ignoring attributes on template argument %qT", arg);
8084   return canon;
8085 }
8086 
8087 /* And from inside dependent non-type arguments like sizeof(Type).  */
8088 
8089 static tree
canonicalize_expr_argument(tree arg,tsubst_flags_t complain)8090 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
8091 {
8092   if (!arg || arg == error_mark_node)
8093     return arg;
8094   bool removed_attributes = false;
8095   tree canon = strip_typedefs_expr (arg, &removed_attributes);
8096   if (removed_attributes
8097       && (complain & tf_warning))
8098     warning (OPT_Wignored_attributes,
8099 	     "ignoring attributes in template argument %qE", arg);
8100   return canon;
8101 }
8102 
8103 /* A template declaration can be substituted for a constrained
8104    template template parameter only when the argument is no more
8105    constrained than the parameter.  */
8106 
8107 static bool
is_compatible_template_arg(tree parm,tree arg)8108 is_compatible_template_arg (tree parm, tree arg)
8109 {
8110   tree parm_cons = get_constraints (parm);
8111 
8112   /* For now, allow constrained template template arguments
8113      and unconstrained template template parameters.  */
8114   if (parm_cons == NULL_TREE)
8115     return true;
8116 
8117   /* If the template parameter is constrained, we need to rewrite its
8118      constraints in terms of the ARG's template parameters. This ensures
8119      that all of the template parameter types will have the same depth.
8120 
8121      Note that this is only valid when coerce_template_template_parm is
8122      true for the innermost template parameters of PARM and ARG. In other
8123      words, because coercion is successful, this conversion will be valid.  */
8124   tree new_args = NULL_TREE;
8125   if (parm_cons)
8126     {
8127       tree aparms = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8128       new_args = template_parms_level_to_args (aparms);
8129       parm_cons = tsubst_constraint_info (parm_cons, new_args,
8130 					  tf_none, NULL_TREE);
8131       if (parm_cons == error_mark_node)
8132         return false;
8133     }
8134 
8135   return weakly_subsumes (parm_cons, new_args, arg);
8136 }
8137 
8138 // Convert a placeholder argument into a binding to the original
8139 // parameter. The original parameter is saved as the TREE_TYPE of
8140 // ARG.
8141 static inline tree
convert_wildcard_argument(tree parm,tree arg)8142 convert_wildcard_argument (tree parm, tree arg)
8143 {
8144   TREE_TYPE (arg) = parm;
8145   return arg;
8146 }
8147 
8148 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
8149    because one of them is dependent.  But we need to represent the
8150    conversion for the benefit of cp_tree_equal.  */
8151 
8152 static tree
maybe_convert_nontype_argument(tree type,tree arg)8153 maybe_convert_nontype_argument (tree type, tree arg)
8154 {
8155   /* Auto parms get no conversion.  */
8156   if (type_uses_auto (type))
8157     return arg;
8158   /* We don't need or want to add this conversion now if we're going to use the
8159      argument for deduction.  */
8160   if (value_dependent_expression_p (arg))
8161     return arg;
8162 
8163   type = cv_unqualified (type);
8164   tree argtype = TREE_TYPE (arg);
8165   if (same_type_p (type, argtype))
8166     return arg;
8167 
8168   arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
8169   IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
8170   return arg;
8171 }
8172 
8173 /* Convert the indicated template ARG as necessary to match the
8174    indicated template PARM.  Returns the converted ARG, or
8175    error_mark_node if the conversion was unsuccessful.  Error and
8176    warning messages are issued under control of COMPLAIN.  This
8177    conversion is for the Ith parameter in the parameter list.  ARGS is
8178    the full set of template arguments deduced so far.  */
8179 
8180 static tree
convert_template_argument(tree parm,tree arg,tree args,tsubst_flags_t complain,int i,tree in_decl)8181 convert_template_argument (tree parm,
8182 			   tree arg,
8183 			   tree args,
8184 			   tsubst_flags_t complain,
8185 			   int i,
8186 			   tree in_decl)
8187 {
8188   tree orig_arg;
8189   tree val;
8190   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
8191 
8192   if (parm == error_mark_node || error_operand_p (arg))
8193     return error_mark_node;
8194 
8195   /* Trivially convert placeholders. */
8196   if (TREE_CODE (arg) == WILDCARD_DECL)
8197     return convert_wildcard_argument (parm, arg);
8198 
8199   if (arg == any_targ_node)
8200     return arg;
8201 
8202   if (TREE_CODE (arg) == TREE_LIST
8203       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
8204     {
8205       /* The template argument was the name of some
8206 	 member function.  That's usually
8207 	 invalid, but static members are OK.  In any
8208 	 case, grab the underlying fields/functions
8209 	 and issue an error later if required.  */
8210       TREE_TYPE (arg) = unknown_type_node;
8211     }
8212 
8213   orig_arg = arg;
8214 
8215   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
8216   requires_type = (TREE_CODE (parm) == TYPE_DECL
8217 		   || requires_tmpl_type);
8218 
8219   /* When determining whether an argument pack expansion is a template,
8220      look at the pattern.  */
8221   if (PACK_EXPANSION_P (arg))
8222     arg = PACK_EXPANSION_PATTERN (arg);
8223 
8224   /* Deal with an injected-class-name used as a template template arg.  */
8225   if (requires_tmpl_type && CLASS_TYPE_P (arg))
8226     {
8227       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
8228       if (TREE_CODE (t) == TEMPLATE_DECL)
8229 	{
8230 	  if (cxx_dialect >= cxx11)
8231 	    /* OK under DR 1004.  */;
8232 	  else if (complain & tf_warning_or_error)
8233 	    pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
8234 		     " used as template template argument", TYPE_NAME (arg));
8235 	  else if (flag_pedantic_errors)
8236 	    t = arg;
8237 
8238 	  arg = t;
8239 	}
8240     }
8241 
8242   is_tmpl_type =
8243     ((TREE_CODE (arg) == TEMPLATE_DECL
8244       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
8245      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
8246      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8247      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
8248 
8249   if (is_tmpl_type
8250       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
8251 	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
8252     arg = TYPE_STUB_DECL (arg);
8253 
8254   is_type = TYPE_P (arg) || is_tmpl_type;
8255 
8256   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
8257       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
8258     {
8259       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
8260 	{
8261 	  if (complain & tf_error)
8262 	    error ("invalid use of destructor %qE as a type", orig_arg);
8263 	  return error_mark_node;
8264 	}
8265 
8266       permerror (input_location,
8267 		 "to refer to a type member of a template parameter, "
8268 		 "use %<typename %E%>", orig_arg);
8269 
8270       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
8271 				     TREE_OPERAND (arg, 1),
8272 				     typename_type,
8273 				     complain);
8274       arg = orig_arg;
8275       is_type = 1;
8276     }
8277   if (is_type != requires_type)
8278     {
8279       if (in_decl)
8280 	{
8281 	  if (complain & tf_error)
8282 	    {
8283 	      error ("type/value mismatch at argument %d in template "
8284 		     "parameter list for %qD",
8285 		     i + 1, in_decl);
8286 	      if (is_type)
8287 		{
8288 		  /* The template argument is a type, but we're expecting
8289 		     an expression.  */
8290 		  inform (input_location,
8291 			  "  expected a constant of type %qT, got %qT",
8292 			  TREE_TYPE (parm),
8293 			  (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
8294 		  /* [temp.arg]/2: "In a template-argument, an ambiguity
8295 		     between a type-id and an expression is resolved to a
8296 		     type-id, regardless of the form of the corresponding
8297 		     template-parameter."  So give the user a clue.  */
8298 		  if (TREE_CODE (arg) == FUNCTION_TYPE)
8299 		    inform (input_location, "  ambiguous template argument "
8300 			    "for non-type template parameter is treated as "
8301 			    "function type");
8302 		}
8303 	      else if (requires_tmpl_type)
8304 		inform (input_location,
8305 			"  expected a class template, got %qE", orig_arg);
8306 	      else
8307 		inform (input_location,
8308 			"  expected a type, got %qE", orig_arg);
8309 	    }
8310 	}
8311       return error_mark_node;
8312     }
8313   if (is_tmpl_type ^ requires_tmpl_type)
8314     {
8315       if (in_decl && (complain & tf_error))
8316 	{
8317 	  error ("type/value mismatch at argument %d in template "
8318 		 "parameter list for %qD",
8319 		 i + 1, in_decl);
8320 	  if (is_tmpl_type)
8321 	    inform (input_location,
8322 		    "  expected a type, got %qT", DECL_NAME (arg));
8323 	  else
8324 	    inform (input_location,
8325 		    "  expected a class template, got %qT", orig_arg);
8326 	}
8327       return error_mark_node;
8328     }
8329 
8330   if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
8331     /* We already did the appropriate conversion when packing args.  */
8332     val = orig_arg;
8333   else if (is_type)
8334     {
8335       if (requires_tmpl_type)
8336 	{
8337 	  if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
8338 	    /* The number of argument required is not known yet.
8339 	       Just accept it for now.  */
8340 	    val = orig_arg;
8341 	  else
8342 	    {
8343 	      tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
8344 	      tree argparm;
8345 
8346 	      /* Strip alias templates that are equivalent to another
8347 		 template.  */
8348 	      arg = get_underlying_template (arg);
8349               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
8350 
8351 	      if (coerce_template_template_parms (parmparm, argparm,
8352 						  complain, in_decl,
8353 						  args))
8354 		{
8355 		  val = arg;
8356 
8357 		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
8358 		     TEMPLATE_DECL.  */
8359 		  if (val != error_mark_node)
8360                     {
8361                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
8362                         val = TREE_TYPE (val);
8363 		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
8364 			val = make_pack_expansion (val, complain);
8365                     }
8366 		}
8367 	      else
8368 		{
8369 		  if (in_decl && (complain & tf_error))
8370 		    {
8371 		      error ("type/value mismatch at argument %d in "
8372 			     "template parameter list for %qD",
8373 			     i + 1, in_decl);
8374 		      inform (input_location,
8375 			      "  expected a template of type %qD, got %qT",
8376 			      parm, orig_arg);
8377 		    }
8378 
8379 		  val = error_mark_node;
8380 		}
8381 
8382               // Check that the constraints are compatible before allowing the
8383               // substitution.
8384               if (val != error_mark_node)
8385                 if (!is_compatible_template_arg (parm, arg))
8386                   {
8387 		    if (in_decl && (complain & tf_error))
8388                       {
8389                         error ("constraint mismatch at argument %d in "
8390                                "template parameter list for %qD",
8391                                i + 1, in_decl);
8392                         inform (input_location, "  expected %qD but got %qD",
8393                                 parm, arg);
8394                       }
8395 		    val = error_mark_node;
8396                   }
8397 	    }
8398 	}
8399       else
8400 	val = orig_arg;
8401       /* We only form one instance of each template specialization.
8402 	 Therefore, if we use a non-canonical variant (i.e., a
8403 	 typedef), any future messages referring to the type will use
8404 	 the typedef, which is confusing if those future uses do not
8405 	 themselves also use the typedef.  */
8406       if (TYPE_P (val))
8407 	val = canonicalize_type_argument (val, complain);
8408     }
8409   else
8410     {
8411       tree t = TREE_TYPE (parm);
8412 
8413       if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
8414 	  > TMPL_ARGS_DEPTH (args))
8415 	/* We don't have enough levels of args to do any substitution.  This
8416 	   can happen in the context of -fnew-ttp-matching.  */;
8417       else if (tree a = type_uses_auto (t))
8418 	{
8419 	  t = do_auto_deduction (t, arg, a, complain, adc_unify, args);
8420 	  if (t == error_mark_node)
8421 	    return error_mark_node;
8422 	}
8423       else
8424 	t = tsubst (t, args, complain, in_decl);
8425 
8426       if (invalid_nontype_parm_type_p (t, complain))
8427 	return error_mark_node;
8428 
8429       if (t != TREE_TYPE (parm))
8430 	t = canonicalize_type_argument (t, complain);
8431 
8432       if (!type_dependent_expression_p (orig_arg)
8433 	  && !uses_template_parms (t))
8434 	/* We used to call digest_init here.  However, digest_init
8435 	   will report errors, which we don't want when complain
8436 	   is zero.  More importantly, digest_init will try too
8437 	   hard to convert things: for example, `0' should not be
8438 	   converted to pointer type at this point according to
8439 	   the standard.  Accepting this is not merely an
8440 	   extension, since deciding whether or not these
8441 	   conversions can occur is part of determining which
8442 	   function template to call, or whether a given explicit
8443 	   argument specification is valid.  */
8444 	val = convert_nontype_argument (t, orig_arg, complain);
8445       else
8446 	{
8447 	  val = canonicalize_expr_argument (orig_arg, complain);
8448 	  val = maybe_convert_nontype_argument (t, val);
8449 	}
8450 
8451 
8452       if (val == NULL_TREE)
8453 	val = error_mark_node;
8454       else if (val == error_mark_node && (complain & tf_error))
8455 	error_at (cp_expr_loc_or_input_loc (orig_arg),
8456 		  "could not convert template argument %qE from %qT to %qT",
8457 		  orig_arg, TREE_TYPE (orig_arg), t);
8458 
8459       if (INDIRECT_REF_P (val))
8460         {
8461           /* Reject template arguments that are references to built-in
8462              functions with no library fallbacks.  */
8463           const_tree inner = TREE_OPERAND (val, 0);
8464 	  const_tree innertype = TREE_TYPE (inner);
8465 	  if (innertype
8466 	      && TYPE_REF_P (innertype)
8467 	      && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8468 	      && TREE_OPERAND_LENGTH (inner) > 0
8469               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8470               return error_mark_node;
8471         }
8472 
8473       if (TREE_CODE (val) == SCOPE_REF)
8474 	{
8475 	  /* Strip typedefs from the SCOPE_REF.  */
8476 	  tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8477 	  tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8478 						   complain);
8479 	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8480 				      QUALIFIED_NAME_IS_TEMPLATE (val));
8481 	}
8482     }
8483 
8484   return val;
8485 }
8486 
8487 /* Coerces the remaining template arguments in INNER_ARGS (from
8488    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8489    Returns the coerced argument pack. PARM_IDX is the position of this
8490    parameter in the template parameter list. ARGS is the original
8491    template argument list.  */
8492 static tree
coerce_template_parameter_pack(tree parms,int parm_idx,tree args,tree inner_args,int arg_idx,tree new_args,int * lost,tree in_decl,tsubst_flags_t complain)8493 coerce_template_parameter_pack (tree parms,
8494                                 int parm_idx,
8495                                 tree args,
8496                                 tree inner_args,
8497                                 int arg_idx,
8498                                 tree new_args,
8499                                 int* lost,
8500                                 tree in_decl,
8501                                 tsubst_flags_t complain)
8502 {
8503   tree parm = TREE_VEC_ELT (parms, parm_idx);
8504   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8505   tree packed_args;
8506   tree argument_pack;
8507   tree packed_parms = NULL_TREE;
8508 
8509   if (arg_idx > nargs)
8510     arg_idx = nargs;
8511 
8512   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8513     {
8514       /* When the template parameter is a non-type template parameter pack
8515          or template template parameter pack whose type or template
8516          parameters use parameter packs, we know exactly how many arguments
8517          we are looking for.  Build a vector of the instantiated decls for
8518          these template parameters in PACKED_PARMS.  */
8519       /* We can't use make_pack_expansion here because it would interpret a
8520 	 _DECL as a use rather than a declaration.  */
8521       tree decl = TREE_VALUE (parm);
8522       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8523       SET_PACK_EXPANSION_PATTERN (exp, decl);
8524       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8525       SET_TYPE_STRUCTURAL_EQUALITY (exp);
8526 
8527       TREE_VEC_LENGTH (args)--;
8528       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8529       TREE_VEC_LENGTH (args)++;
8530 
8531       if (packed_parms == error_mark_node)
8532         return error_mark_node;
8533 
8534       /* If we're doing a partial instantiation of a member template,
8535          verify that all of the types used for the non-type
8536          template parameter pack are, in fact, valid for non-type
8537          template parameters.  */
8538       if (arg_idx < nargs
8539           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8540         {
8541           int j, len = TREE_VEC_LENGTH (packed_parms);
8542           for (j = 0; j < len; ++j)
8543             {
8544               tree t = TREE_VEC_ELT (packed_parms, j);
8545               if (TREE_CODE (t) == PARM_DECL
8546 		  && invalid_nontype_parm_type_p (TREE_TYPE (t), complain))
8547                 return error_mark_node;
8548             }
8549 	  /* We don't know how many args we have yet, just
8550 	     use the unconverted ones for now.  */
8551 	  return NULL_TREE;
8552         }
8553 
8554       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8555     }
8556   /* Check if we have a placeholder pack, which indicates we're
8557      in the context of a introduction list.  In that case we want
8558      to match this pack to the single placeholder.  */
8559   else if (arg_idx < nargs
8560            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8561            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8562     {
8563       nargs = arg_idx + 1;
8564       packed_args = make_tree_vec (1);
8565     }
8566   else
8567     packed_args = make_tree_vec (nargs - arg_idx);
8568 
8569   /* Convert the remaining arguments, which will be a part of the
8570      parameter pack "parm".  */
8571   int first_pack_arg = arg_idx;
8572   for (; arg_idx < nargs; ++arg_idx)
8573     {
8574       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8575       tree actual_parm = TREE_VALUE (parm);
8576       int pack_idx = arg_idx - first_pack_arg;
8577 
8578       if (packed_parms)
8579         {
8580 	  /* Once we've packed as many args as we have types, stop.  */
8581 	  if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8582 	    break;
8583 	  else if (PACK_EXPANSION_P (arg))
8584 	    /* We don't know how many args we have yet, just
8585 	       use the unconverted ones for now.  */
8586 	    return NULL_TREE;
8587 	  else
8588 	    actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8589         }
8590 
8591       if (arg == error_mark_node)
8592 	{
8593 	  if (complain & tf_error)
8594 	    error ("template argument %d is invalid", arg_idx + 1);
8595 	}
8596       else
8597 	arg = convert_template_argument (actual_parm,
8598 					 arg, new_args, complain, parm_idx,
8599 					 in_decl);
8600       if (arg == error_mark_node)
8601         (*lost)++;
8602       TREE_VEC_ELT (packed_args, pack_idx) = arg;
8603     }
8604 
8605   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8606       && TREE_VEC_LENGTH (packed_args) > 0)
8607     {
8608       if (complain & tf_error)
8609 	error ("wrong number of template arguments (%d, should be %d)",
8610 	       arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8611       return error_mark_node;
8612     }
8613 
8614   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8615       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8616     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8617   else
8618     {
8619       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8620       TREE_CONSTANT (argument_pack) = 1;
8621     }
8622 
8623   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8624   if (CHECKING_P)
8625     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8626 					 TREE_VEC_LENGTH (packed_args));
8627   return argument_pack;
8628 }
8629 
8630 /* Returns the number of pack expansions in the template argument vector
8631    ARGS.  */
8632 
8633 static int
pack_expansion_args_count(tree args)8634 pack_expansion_args_count (tree args)
8635 {
8636   int i;
8637   int count = 0;
8638   if (args)
8639     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8640       {
8641 	tree elt = TREE_VEC_ELT (args, i);
8642 	if (elt && PACK_EXPANSION_P (elt))
8643 	  ++count;
8644       }
8645   return count;
8646 }
8647 
8648 /* Convert all template arguments to their appropriate types, and
8649    return a vector containing the innermost resulting template
8650    arguments.  If any error occurs, return error_mark_node. Error and
8651    warning messages are issued under control of COMPLAIN.
8652 
8653    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8654    for arguments not specified in ARGS.  Otherwise, if
8655    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8656    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
8657    USE_DEFAULT_ARGS is false, then all arguments must be specified in
8658    ARGS.  */
8659 
8660 static tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)8661 coerce_template_parms (tree parms,
8662 		       tree args,
8663 		       tree in_decl,
8664 		       tsubst_flags_t complain,
8665 		       bool require_all_args,
8666 		       bool use_default_args)
8667 {
8668   int nparms, nargs, parm_idx, arg_idx, lost = 0;
8669   tree orig_inner_args;
8670   tree inner_args;
8671   tree new_args;
8672   tree new_inner_args;
8673 
8674   /* When used as a boolean value, indicates whether this is a
8675      variadic template parameter list. Since it's an int, we can also
8676      subtract it from nparms to get the number of non-variadic
8677      parameters.  */
8678   int variadic_p = 0;
8679   int variadic_args_p = 0;
8680   int post_variadic_parms = 0;
8681 
8682   /* Adjustment to nparms for fixed parameter packs.  */
8683   int fixed_pack_adjust = 0;
8684   int fixed_packs = 0;
8685   int missing = 0;
8686 
8687   /* Likewise for parameters with default arguments.  */
8688   int default_p = 0;
8689 
8690   if (args == error_mark_node)
8691     return error_mark_node;
8692 
8693   nparms = TREE_VEC_LENGTH (parms);
8694 
8695   /* Determine if there are any parameter packs or default arguments.  */
8696   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8697     {
8698       tree parm = TREE_VEC_ELT (parms, parm_idx);
8699       if (variadic_p)
8700 	++post_variadic_parms;
8701       if (template_parameter_pack_p (TREE_VALUE (parm)))
8702 	++variadic_p;
8703       if (TREE_PURPOSE (parm))
8704 	++default_p;
8705     }
8706 
8707   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8708   /* If there are no parameters that follow a parameter pack, we need to
8709      expand any argument packs so that we can deduce a parameter pack from
8710      some non-packed args followed by an argument pack, as in variadic85.C.
8711      If there are such parameters, we need to leave argument packs intact
8712      so the arguments are assigned properly.  This can happen when dealing
8713      with a nested class inside a partial specialization of a class
8714      template, as in variadic92.C, or when deducing a template parameter pack
8715      from a sub-declarator, as in variadic114.C.  */
8716   if (!post_variadic_parms)
8717     inner_args = expand_template_argument_pack (inner_args);
8718 
8719   /* Count any pack expansion args.  */
8720   variadic_args_p = pack_expansion_args_count (inner_args);
8721 
8722   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8723   if ((nargs - variadic_args_p > nparms && !variadic_p)
8724       || (nargs < nparms - variadic_p
8725 	  && require_all_args
8726 	  && !variadic_args_p
8727 	  && (!use_default_args
8728 	      || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8729                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8730     {
8731     bad_nargs:
8732       if (complain & tf_error)
8733 	{
8734           if (variadic_p || default_p)
8735             {
8736               nparms -= variadic_p + default_p;
8737 	      error ("wrong number of template arguments "
8738 		     "(%d, should be at least %d)", nargs, nparms);
8739             }
8740 	  else
8741 	     error ("wrong number of template arguments "
8742 		    "(%d, should be %d)", nargs, nparms);
8743 
8744 	  if (in_decl)
8745 	    inform (DECL_SOURCE_LOCATION (in_decl),
8746 		    "provided for %qD", in_decl);
8747 	}
8748 
8749       return error_mark_node;
8750     }
8751   /* We can't pass a pack expansion to a non-pack parameter of an alias
8752      template (DR 1430).  */
8753   else if (in_decl
8754 	   && (DECL_ALIAS_TEMPLATE_P (in_decl)
8755 	       || concept_definition_p (in_decl))
8756 	   && variadic_args_p
8757 	   && nargs - variadic_args_p < nparms - variadic_p)
8758     {
8759       if (complain & tf_error)
8760 	{
8761 	  for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8762 	    {
8763 	      tree arg = TREE_VEC_ELT (inner_args, i);
8764 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8765 
8766 	      if (PACK_EXPANSION_P (arg)
8767 		  && !template_parameter_pack_p (parm))
8768 		{
8769 		  if (DECL_ALIAS_TEMPLATE_P (in_decl))
8770 		    error_at (location_of (arg),
8771 			      "pack expansion argument for non-pack parameter "
8772 			      "%qD of alias template %qD", parm, in_decl);
8773 		  else
8774 		    error_at (location_of (arg),
8775 			      "pack expansion argument for non-pack parameter "
8776 			      "%qD of concept %qD", parm, in_decl);
8777 		  inform (DECL_SOURCE_LOCATION (parm), "declared here");
8778 		  goto found;
8779 		}
8780 	    }
8781 	  gcc_unreachable ();
8782 	found:;
8783 	}
8784       return error_mark_node;
8785     }
8786 
8787   /* We need to evaluate the template arguments, even though this
8788      template-id may be nested within a "sizeof".  */
8789   cp_evaluated ev;
8790 
8791   new_inner_args = make_tree_vec (nparms);
8792   new_args = add_outermost_template_args (args, new_inner_args);
8793   int pack_adjust = 0;
8794   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
8795     {
8796       tree arg;
8797       tree parm;
8798 
8799       /* Get the Ith template parameter.  */
8800       parm = TREE_VEC_ELT (parms, parm_idx);
8801 
8802       if (parm == error_mark_node)
8803 	{
8804 	  TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
8805 	  continue;
8806 	}
8807 
8808       /* Calculate the next argument.  */
8809       if (arg_idx < nargs)
8810 	arg = TREE_VEC_ELT (inner_args, arg_idx);
8811       else
8812 	arg = NULL_TREE;
8813 
8814       if (template_parameter_pack_p (TREE_VALUE (parm))
8815 	  && (arg || require_all_args || !(complain & tf_partial))
8816 	  && !(arg && ARGUMENT_PACK_P (arg)))
8817         {
8818 	  /* Some arguments will be placed in the
8819 	     template parameter pack PARM.  */
8820 	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
8821 						inner_args, arg_idx,
8822 						new_args, &lost,
8823 						in_decl, complain);
8824 
8825 	  if (arg == NULL_TREE)
8826 	    {
8827 	      /* We don't know how many args we have yet, just use the
8828 		 unconverted (and still packed) ones for now.  */
8829 	      new_inner_args = orig_inner_args;
8830 	      arg_idx = nargs;
8831 	      break;
8832 	    }
8833 
8834           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
8835 
8836           /* Store this argument.  */
8837           if (arg == error_mark_node)
8838 	    {
8839 	      lost++;
8840 	      /* We are done with all of the arguments.  */
8841 	      arg_idx = nargs;
8842 	      break;
8843 	    }
8844 	  else
8845 	    {
8846 	      pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
8847 	      arg_idx += pack_adjust;
8848 	      if (fixed_parameter_pack_p (TREE_VALUE (parm)))
8849 		{
8850 		  ++fixed_packs;
8851 		  fixed_pack_adjust += pack_adjust;
8852 		}
8853 	    }
8854 
8855           continue;
8856         }
8857       else if (arg)
8858 	{
8859           if (PACK_EXPANSION_P (arg))
8860             {
8861 	      /* "If every valid specialization of a variadic template
8862 		 requires an empty template parameter pack, the template is
8863 		 ill-formed, no diagnostic required."  So check that the
8864 		 pattern works with this parameter.  */
8865 	      tree pattern = PACK_EXPANSION_PATTERN (arg);
8866 	      tree conv = convert_template_argument (TREE_VALUE (parm),
8867 						     pattern, new_args,
8868 						     complain, parm_idx,
8869 						     in_decl);
8870 	      if (conv == error_mark_node)
8871 		{
8872 		  if (complain & tf_error)
8873 		    inform (input_location, "so any instantiation with a "
8874 			    "non-empty parameter pack would be ill-formed");
8875 		  ++lost;
8876 		}
8877 	      else if (TYPE_P (conv) && !TYPE_P (pattern))
8878 		/* Recover from missing typename.  */
8879 		TREE_VEC_ELT (inner_args, arg_idx)
8880 		  = make_pack_expansion (conv, complain);
8881 
8882               /* We don't know how many args we have yet, just
8883                  use the unconverted ones for now.  */
8884               new_inner_args = inner_args;
8885 	      arg_idx = nargs;
8886               break;
8887             }
8888         }
8889       else if (require_all_args)
8890 	{
8891 	  /* There must be a default arg in this case.  */
8892 	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
8893 				     complain, in_decl);
8894 	  /* The position of the first default template argument,
8895 	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
8896 	     Record that.  */
8897 	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8898 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8899 						 arg_idx - pack_adjust);
8900 	}
8901       else
8902 	break;
8903 
8904       if (arg == error_mark_node)
8905 	{
8906 	  if (complain & tf_error)
8907 	    error ("template argument %d is invalid", arg_idx + 1);
8908 	}
8909       else if (!arg)
8910 	{
8911 	  /* This can occur if there was an error in the template
8912 	     parameter list itself (which we would already have
8913 	     reported) that we are trying to recover from, e.g., a class
8914 	     template with a parameter list such as
8915 	     template<typename..., typename> (cpp0x/variadic150.C).  */
8916 	  ++lost;
8917 
8918 	  /* This can also happen with a fixed parameter pack (71834).  */
8919 	  if (arg_idx >= nargs)
8920 	    ++missing;
8921 	}
8922       else
8923 	arg = convert_template_argument (TREE_VALUE (parm),
8924 					 arg, new_args, complain,
8925                                          parm_idx, in_decl);
8926 
8927       if (arg == error_mark_node)
8928 	lost++;
8929 
8930       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
8931     }
8932 
8933   if (missing || arg_idx < nargs - variadic_args_p)
8934     {
8935       /* If we had fixed parameter packs, we didn't know how many arguments we
8936 	 actually needed earlier; now we do.  */
8937       nparms += fixed_pack_adjust;
8938       variadic_p -= fixed_packs;
8939       goto bad_nargs;
8940     }
8941 
8942   if (arg_idx < nargs)
8943     {
8944       /* We had some pack expansion arguments that will only work if the packs
8945 	 are empty, but wait until instantiation time to complain.
8946 	 See variadic-ttp3.C.  */
8947 
8948       /* Except that we can't provide empty packs to alias templates or
8949          concepts when there are no corresponding parameters. Basically,
8950          we can get here with this:
8951 
8952              template<typename T> concept C = true;
8953 
8954              template<typename... Args>
8955 	       requires C<Args...>
8956              void f();
8957 
8958          When parsing C<Args...>, we try to form a concept check of
8959          C<?, Args...>. Without the extra check for substituting an empty
8960          pack past the last parameter, we can accept the check as valid.
8961 
8962          FIXME: This may be valid for alias templates (but I doubt it).
8963 
8964          FIXME: The error could be better also.   */
8965       if (in_decl && concept_definition_p (in_decl))
8966 	{
8967 	  if (complain & tf_error)
8968 	    error_at (location_of (TREE_VEC_ELT (args, arg_idx)),
8969 		      "too many arguments");
8970 	  return error_mark_node;
8971 	}
8972 
8973       int len = nparms + (nargs - arg_idx);
8974       tree args = make_tree_vec (len);
8975       int i = 0;
8976       for (; i < nparms; ++i)
8977 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
8978       for (; i < len; ++i, ++arg_idx)
8979 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
8980 					       arg_idx - pack_adjust);
8981       new_inner_args = args;
8982     }
8983 
8984   if (lost)
8985     {
8986       gcc_assert (!(complain & tf_error) || seen_error ());
8987       return error_mark_node;
8988     }
8989 
8990   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8991     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8992 					 TREE_VEC_LENGTH (new_inner_args));
8993 
8994   return new_inner_args;
8995 }
8996 
8997 /* Convert all template arguments to their appropriate types, and
8998    return a vector containing the innermost resulting template
8999    arguments.  If any error occurs, return error_mark_node. Error and
9000    warning messages are not issued.
9001 
9002    Note that no function argument deduction is performed, and default
9003    arguments are used to fill in unspecified arguments. */
9004 tree
coerce_template_parms(tree parms,tree args,tree in_decl)9005 coerce_template_parms (tree parms, tree args, tree in_decl)
9006 {
9007   return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
9008 }
9009 
9010 /* Convert all template arguments to their appropriate type, and
9011    instantiate default arguments as needed. This returns a vector
9012    containing the innermost resulting template arguments, or
9013    error_mark_node if unsuccessful.  */
9014 tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain)9015 coerce_template_parms (tree parms, tree args, tree in_decl,
9016                        tsubst_flags_t complain)
9017 {
9018   return coerce_template_parms (parms, args, in_decl, complain, true, true);
9019 }
9020 
9021 /* Like coerce_template_parms.  If PARMS represents all template
9022    parameters levels, this function returns a vector of vectors
9023    representing all the resulting argument levels.  Note that in this
9024    case, only the innermost arguments are coerced because the
9025    outermost ones are supposed to have been coerced already.
9026 
9027    Otherwise, if PARMS represents only (the innermost) vector of
9028    parameters, this function returns a vector containing just the
9029    innermost resulting arguments.  */
9030 
9031 static tree
coerce_innermost_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)9032 coerce_innermost_template_parms (tree parms,
9033 				  tree args,
9034 				  tree in_decl,
9035 				  tsubst_flags_t complain,
9036 				  bool require_all_args,
9037 				  bool use_default_args)
9038 {
9039   int parms_depth = TMPL_PARMS_DEPTH (parms);
9040   int args_depth = TMPL_ARGS_DEPTH (args);
9041   tree coerced_args;
9042 
9043   if (parms_depth > 1)
9044     {
9045       coerced_args = make_tree_vec (parms_depth);
9046       tree level;
9047       int cur_depth;
9048 
9049       for (level = parms, cur_depth = parms_depth;
9050 	   parms_depth > 0 && level != NULL_TREE;
9051 	   level = TREE_CHAIN (level), --cur_depth)
9052 	{
9053 	  tree l;
9054 	  if (cur_depth == args_depth)
9055 	    l = coerce_template_parms (TREE_VALUE (level),
9056 				       args, in_decl, complain,
9057 				       require_all_args,
9058 				       use_default_args);
9059 	  else
9060 	    l = TMPL_ARGS_LEVEL (args, cur_depth);
9061 
9062 	  if (l == error_mark_node)
9063 	    return error_mark_node;
9064 
9065 	  SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
9066 	}
9067     }
9068   else
9069     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
9070 					  args, in_decl, complain,
9071 					  require_all_args,
9072 					  use_default_args);
9073   return coerced_args;
9074 }
9075 
9076 /* Returns true if T is a wrapper to make a C++20 template parameter
9077    object const.  */
9078 
9079 static bool
class_nttp_const_wrapper_p(tree t)9080 class_nttp_const_wrapper_p (tree t)
9081 {
9082   if (cxx_dialect < cxx2a)
9083     return false;
9084   return (TREE_CODE (t) == VIEW_CONVERT_EXPR
9085 	  && CP_TYPE_CONST_P (TREE_TYPE (t))
9086 	  && TREE_CODE (TREE_OPERAND (t, 0)) == TEMPLATE_PARM_INDEX);
9087 }
9088 
9089 /* Returns 1 if template args OT and NT are equivalent.  */
9090 
9091 int
template_args_equal(tree ot,tree nt,bool partial_order)9092 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
9093 {
9094   if (nt == ot)
9095     return 1;
9096   if (nt == NULL_TREE || ot == NULL_TREE)
9097     return false;
9098   if (nt == any_targ_node || ot == any_targ_node)
9099     return true;
9100 
9101   if (class_nttp_const_wrapper_p (nt))
9102     nt = TREE_OPERAND (nt, 0);
9103   if (class_nttp_const_wrapper_p (ot))
9104     ot = TREE_OPERAND (ot, 0);
9105 
9106   if (TREE_CODE (nt) == TREE_VEC)
9107     /* For member templates */
9108     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
9109   else if (PACK_EXPANSION_P (ot))
9110     return (PACK_EXPANSION_P (nt)
9111 	    && template_args_equal (PACK_EXPANSION_PATTERN (ot),
9112 				    PACK_EXPANSION_PATTERN (nt))
9113 	    && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
9114 				    PACK_EXPANSION_EXTRA_ARGS (nt)));
9115   else if (ARGUMENT_PACK_P (ot) || ARGUMENT_PACK_P (nt))
9116     return cp_tree_equal (ot, nt);
9117   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
9118     gcc_unreachable ();
9119   else if (TYPE_P (nt))
9120     {
9121       if (!TYPE_P (ot))
9122 	return false;
9123       /* Don't treat an alias template specialization with dependent
9124 	 arguments as equivalent to its underlying type when used as a
9125 	 template argument; we need them to be distinct so that we
9126 	 substitute into the specialization arguments at instantiation
9127 	 time.  And aliases can't be equivalent without being ==, so
9128 	 we don't need to look any deeper.
9129 
9130          During partial ordering, however, we need to treat them normally so
9131          that we can order uses of the same alias with different
9132          cv-qualification (79960).  */
9133       if (!partial_order
9134 	  && (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot)))
9135 	return false;
9136       else
9137 	return same_type_p (ot, nt);
9138     }
9139   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
9140     return 0;
9141   else
9142     {
9143       /* Try to treat a template non-type argument that has been converted
9144 	 to the parameter type as equivalent to one that hasn't yet.  */
9145       for (enum tree_code code1 = TREE_CODE (ot);
9146 	   CONVERT_EXPR_CODE_P (code1)
9147 	     || code1 == NON_LVALUE_EXPR;
9148 	   code1 = TREE_CODE (ot))
9149 	ot = TREE_OPERAND (ot, 0);
9150       for (enum tree_code code2 = TREE_CODE (nt);
9151 	   CONVERT_EXPR_CODE_P (code2)
9152 	     || code2 == NON_LVALUE_EXPR;
9153 	   code2 = TREE_CODE (nt))
9154 	nt = TREE_OPERAND (nt, 0);
9155 
9156       return cp_tree_equal (ot, nt);
9157     }
9158 }
9159 
9160 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
9161    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
9162    NEWARG_PTR with the offending arguments if they are non-NULL.  */
9163 
9164 int
comp_template_args(tree oldargs,tree newargs,tree * oldarg_ptr,tree * newarg_ptr,bool partial_order)9165 comp_template_args (tree oldargs, tree newargs,
9166 		    tree *oldarg_ptr, tree *newarg_ptr,
9167 		    bool partial_order)
9168 {
9169   int i;
9170 
9171   if (oldargs == newargs)
9172     return 1;
9173 
9174   if (!oldargs || !newargs)
9175     return 0;
9176 
9177   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
9178     return 0;
9179 
9180   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
9181     {
9182       tree nt = TREE_VEC_ELT (newargs, i);
9183       tree ot = TREE_VEC_ELT (oldargs, i);
9184 
9185       if (! template_args_equal (ot, nt, partial_order))
9186 	{
9187 	  if (oldarg_ptr != NULL)
9188 	    *oldarg_ptr = ot;
9189 	  if (newarg_ptr != NULL)
9190 	    *newarg_ptr = nt;
9191 	  return 0;
9192 	}
9193     }
9194   return 1;
9195 }
9196 
9197 inline bool
comp_template_args_porder(tree oargs,tree nargs)9198 comp_template_args_porder (tree oargs, tree nargs)
9199 {
9200   return comp_template_args (oargs, nargs, NULL, NULL, true);
9201 }
9202 
9203 /* Implement a freelist interface for objects of type T.
9204 
9205    Head is a separate object, rather than a regular member, so that we
9206    can define it as a GTY deletable pointer, which is highly
9207    desirable.  A data member could be declared that way, but then the
9208    containing object would implicitly get GTY((user)), which would
9209    prevent us from instantiating freelists as global objects.
9210    Although this way we can create freelist global objects, they're
9211    such thin wrappers that instantiating temporaries at every use
9212    loses nothing and saves permanent storage for the freelist object.
9213 
9214    Member functions next, anew, poison and reinit have default
9215    implementations that work for most of the types we're interested
9216    in, but if they don't work for some type, they should be explicitly
9217    specialized.  See the comments before them for requirements, and
9218    the example specializations for the tree_list_freelist.  */
9219 template <typename T>
9220 class freelist
9221 {
9222   /* Return the next object in a chain.  We could just do type
9223      punning, but if we access the object with its underlying type, we
9224      avoid strict-aliasing trouble.  This needs only work between
9225      poison and reinit.  */
next(T * obj)9226   static T *&next (T *obj) { return obj->next; }
9227 
9228   /* Return a newly allocated, uninitialized or minimally-initialized
9229      object of type T.  Any initialization performed by anew should
9230      either remain across the life of the object and the execution of
9231      poison, or be redone by reinit.  */
anew()9232   static T *anew () { return ggc_alloc<T> (); }
9233 
9234   /* Optionally scribble all over the bits holding the object, so that
9235      they become (mostly?) uninitialized memory.  This is called while
9236      preparing to make the object part of the free list.  */
poison(T * obj)9237   static void poison (T *obj) {
9238     T *p ATTRIBUTE_UNUSED = obj;
9239     T **q ATTRIBUTE_UNUSED = &next (obj);
9240 
9241 #ifdef ENABLE_GC_CHECKING
9242     /* Poison the data, to indicate the data is garbage.  */
9243     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
9244     memset (p, 0xa5, sizeof (*p));
9245 #endif
9246     /* Let valgrind know the object is free.  */
9247     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
9248 
9249     /* Let valgrind know the next portion of the object is available,
9250        but uninitialized.  */
9251     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9252   }
9253 
9254   /* Bring an object that underwent at least one lifecycle after anew
9255      and before the most recent free and poison, back to a usable
9256      state, reinitializing whatever is needed for it to be
9257      functionally equivalent to an object just allocated and returned
9258      by anew.  This may poison or clear the next field, used by
9259      freelist housekeeping after poison was called.  */
reinit(T * obj)9260   static void reinit (T *obj) {
9261     T **q ATTRIBUTE_UNUSED = &next (obj);
9262 
9263 #ifdef ENABLE_GC_CHECKING
9264     memset (q, 0xa5, sizeof (*q));
9265 #endif
9266     /* Let valgrind know the entire object is available, but
9267        uninitialized.  */
9268     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
9269   }
9270 
9271   /* Reference a GTY-deletable pointer that points to the first object
9272      in the free list proper.  */
9273   T *&head;
9274 public:
9275   /* Construct a freelist object chaining objects off of HEAD.  */
freelist(T * & head)9276   freelist (T *&head) : head(head) {}
9277 
9278   /* Add OBJ to the free object list.  The former head becomes OBJ's
9279      successor.  */
free(T * obj)9280   void free (T *obj)
9281   {
9282     poison (obj);
9283     next (obj) = head;
9284     head = obj;
9285   }
9286 
9287   /* Take an object from the free list, if one is available, or
9288      allocate a new one.  Objects taken from the free list should be
9289      regarded as filled with garbage, except for bits that are
9290      configured to be preserved across free and alloc.  */
alloc()9291   T *alloc ()
9292   {
9293     if (head)
9294       {
9295 	T *obj = head;
9296 	head = next (head);
9297 	reinit (obj);
9298 	return obj;
9299       }
9300     else
9301       return anew ();
9302   }
9303 };
9304 
9305 /* Explicitly specialize the interfaces for freelist<tree_node>: we
9306    want to allocate a TREE_LIST using the usual interface, and ensure
9307    TREE_CHAIN remains functional.  Alas, we have to duplicate a bit of
9308    build_tree_list logic in reinit, so this could go out of sync.  */
9309 template <>
9310 inline tree &
next(tree obj)9311 freelist<tree_node>::next (tree obj)
9312 {
9313   return TREE_CHAIN (obj);
9314 }
9315 template <>
9316 inline tree
anew()9317 freelist<tree_node>::anew ()
9318 {
9319   return build_tree_list (NULL, NULL);
9320 }
9321 template <>
9322 inline void
poison(tree obj ATTRIBUTE_UNUSED)9323 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
9324 {
9325   int size ATTRIBUTE_UNUSED = sizeof (tree_list);
9326   tree p ATTRIBUTE_UNUSED = obj;
9327   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9328   tree *q ATTRIBUTE_UNUSED = &next (obj);
9329 
9330 #ifdef ENABLE_GC_CHECKING
9331   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9332 
9333   /* Poison the data, to indicate the data is garbage.  */
9334   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
9335   memset (p, 0xa5, size);
9336 #endif
9337   /* Let valgrind know the object is free.  */
9338   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
9339   /* But we still want to use the TREE_CODE and TREE_CHAIN parts.  */
9340   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9341   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
9342 
9343 #ifdef ENABLE_GC_CHECKING
9344   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
9345   /* Keep TREE_CHAIN functional.  */
9346   TREE_SET_CODE (obj, TREE_LIST);
9347 #else
9348   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9349 #endif
9350 }
9351 template <>
9352 inline void
reinit(tree obj ATTRIBUTE_UNUSED)9353 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
9354 {
9355   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
9356 
9357 #ifdef ENABLE_GC_CHECKING
9358   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
9359   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9360   memset (obj, 0, sizeof (tree_list));
9361 #endif
9362 
9363   /* Let valgrind know the entire object is available, but
9364      uninitialized.  */
9365   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
9366 
9367 #ifdef ENABLE_GC_CHECKING
9368   TREE_SET_CODE (obj, TREE_LIST);
9369 #else
9370   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
9371 #endif
9372 }
9373 
9374 /* Point to the first object in the TREE_LIST freelist.  */
9375 static GTY((deletable)) tree tree_list_freelist_head;
9376 /* Return the/an actual TREE_LIST freelist.  */
9377 static inline freelist<tree_node>
tree_list_freelist()9378 tree_list_freelist ()
9379 {
9380   return tree_list_freelist_head;
9381 }
9382 
9383 /* Point to the first object in the tinst_level freelist.  */
9384 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
9385 /* Return the/an actual tinst_level freelist.  */
9386 static inline freelist<tinst_level>
tinst_level_freelist()9387 tinst_level_freelist ()
9388 {
9389   return tinst_level_freelist_head;
9390 }
9391 
9392 /* Point to the first object in the pending_template freelist.  */
9393 static GTY((deletable)) pending_template *pending_template_freelist_head;
9394 /* Return the/an actual pending_template freelist.  */
9395 static inline freelist<pending_template>
pending_template_freelist()9396 pending_template_freelist ()
9397 {
9398   return pending_template_freelist_head;
9399 }
9400 
9401 /* Build the TREE_LIST object out of a split list, store it
9402    permanently, and return it.  */
9403 tree
to_list()9404 tinst_level::to_list ()
9405 {
9406   gcc_assert (split_list_p ());
9407   tree ret = tree_list_freelist ().alloc ();
9408   TREE_PURPOSE (ret) = tldcl;
9409   TREE_VALUE (ret) = targs;
9410   tldcl = ret;
9411   targs = NULL;
9412   gcc_assert (tree_list_p ());
9413   return ret;
9414 }
9415 
9416 const unsigned short tinst_level::refcount_infinity;
9417 
9418 /* Increment OBJ's refcount unless it is already infinite.  */
9419 static tinst_level *
inc_refcount_use(tinst_level * obj)9420 inc_refcount_use (tinst_level *obj)
9421 {
9422   if (obj && obj->refcount != tinst_level::refcount_infinity)
9423     ++obj->refcount;
9424   return obj;
9425 }
9426 
9427 /* Release storage for OBJ and node, if it's a TREE_LIST.  */
9428 void
free(tinst_level * obj)9429 tinst_level::free (tinst_level *obj)
9430 {
9431   if (obj->tree_list_p ())
9432     tree_list_freelist ().free (obj->get_node ());
9433   tinst_level_freelist ().free (obj);
9434 }
9435 
9436 /* Decrement OBJ's refcount if not infinite.  If it reaches zero, release
9437    OBJ's DECL and OBJ, and start over with the tinst_level object that
9438    used to be referenced by OBJ's NEXT.  */
9439 static void
dec_refcount_use(tinst_level * obj)9440 dec_refcount_use (tinst_level *obj)
9441 {
9442   while (obj
9443 	 && obj->refcount != tinst_level::refcount_infinity
9444 	 && !--obj->refcount)
9445     {
9446       tinst_level *next = obj->next;
9447       tinst_level::free (obj);
9448       obj = next;
9449     }
9450 }
9451 
9452 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
9453    and of the former PTR.  Omitting the second argument is equivalent
9454    to passing (T*)NULL; this is allowed because passing the
9455    zero-valued integral constant NULL confuses type deduction and/or
9456    overload resolution.  */
9457 template <typename T>
9458 static void
9459 set_refcount_ptr (T *& ptr, T *obj = NULL)
9460 {
9461   T *save = ptr;
9462   ptr = inc_refcount_use (obj);
9463   dec_refcount_use (save);
9464 }
9465 
9466 static void
add_pending_template(tree d)9467 add_pending_template (tree d)
9468 {
9469   tree ti = (TYPE_P (d)
9470 	     ? CLASSTYPE_TEMPLATE_INFO (d)
9471 	     : DECL_TEMPLATE_INFO (d));
9472   struct pending_template *pt;
9473   int level;
9474 
9475   if (TI_PENDING_TEMPLATE_FLAG (ti))
9476     return;
9477 
9478   /* We are called both from instantiate_decl, where we've already had a
9479      tinst_level pushed, and instantiate_template, where we haven't.
9480      Compensate.  */
9481   gcc_assert (TREE_CODE (d) != TREE_LIST);
9482   level = !current_tinst_level
9483     || current_tinst_level->maybe_get_node () != d;
9484 
9485   if (level)
9486     push_tinst_level (d);
9487 
9488   pt = pending_template_freelist ().alloc ();
9489   pt->next = NULL;
9490   pt->tinst = NULL;
9491   set_refcount_ptr (pt->tinst, current_tinst_level);
9492   if (last_pending_template)
9493     last_pending_template->next = pt;
9494   else
9495     pending_templates = pt;
9496 
9497   last_pending_template = pt;
9498 
9499   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9500 
9501   if (level)
9502     pop_tinst_level ();
9503 }
9504 
9505 
9506 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9507    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
9508    documentation for TEMPLATE_ID_EXPR.  */
9509 
9510 tree
lookup_template_function(tree fns,tree arglist)9511 lookup_template_function (tree fns, tree arglist)
9512 {
9513   if (fns == error_mark_node || arglist == error_mark_node)
9514     return error_mark_node;
9515 
9516   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9517 
9518   if (!is_overloaded_fn (fns) && !identifier_p (fns))
9519     {
9520       error ("%q#D is not a function template", fns);
9521       return error_mark_node;
9522     }
9523 
9524   if (BASELINK_P (fns))
9525     {
9526       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9527 					 unknown_type_node,
9528 					 BASELINK_FUNCTIONS (fns),
9529 					 arglist);
9530       return fns;
9531     }
9532 
9533   return build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, arglist);
9534 }
9535 
9536 /* Within the scope of a template class S<T>, the name S gets bound
9537    (in build_self_reference) to a TYPE_DECL for the class, not a
9538    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
9539    or one of its enclosing classes, and that type is a template,
9540    return the associated TEMPLATE_DECL.  Otherwise, the original
9541    DECL is returned.
9542 
9543    Also handle the case when DECL is a TREE_LIST of ambiguous
9544    injected-class-names from different bases.  */
9545 
9546 tree
maybe_get_template_decl_from_type_decl(tree decl)9547 maybe_get_template_decl_from_type_decl (tree decl)
9548 {
9549   if (decl == NULL_TREE)
9550     return decl;
9551 
9552   /* DR 176: A lookup that finds an injected-class-name (10.2
9553      [class.member.lookup]) can result in an ambiguity in certain cases
9554      (for example, if it is found in more than one base class). If all of
9555      the injected-class-names that are found refer to specializations of
9556      the same class template, and if the name is followed by a
9557      template-argument-list, the reference refers to the class template
9558      itself and not a specialization thereof, and is not ambiguous.  */
9559   if (TREE_CODE (decl) == TREE_LIST)
9560     {
9561       tree t, tmpl = NULL_TREE;
9562       for (t = decl; t; t = TREE_CHAIN (t))
9563 	{
9564 	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9565 	  if (!tmpl)
9566 	    tmpl = elt;
9567 	  else if (tmpl != elt)
9568 	    break;
9569 	}
9570       if (tmpl && t == NULL_TREE)
9571 	return tmpl;
9572       else
9573 	return decl;
9574     }
9575 
9576   return (decl != NULL_TREE
9577 	  && DECL_SELF_REFERENCE_P (decl)
9578 	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9579     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9580 }
9581 
9582 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9583    parameters, find the desired type.
9584 
9585    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9586 
9587    IN_DECL, if non-NULL, is the template declaration we are trying to
9588    instantiate.
9589 
9590    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9591    the class we are looking up.
9592 
9593    Issue error and warning messages under control of COMPLAIN.
9594 
9595    If the template class is really a local class in a template
9596    function, then the FUNCTION_CONTEXT is the function in which it is
9597    being instantiated.
9598 
9599    ??? Note that this function is currently called *twice* for each
9600    template-id: the first time from the parser, while creating the
9601    incomplete type (finish_template_type), and the second type during the
9602    real instantiation (instantiate_template_class). This is surely something
9603    that we want to avoid. It also causes some problems with argument
9604    coercion (see convert_nontype_argument for more information on this).  */
9605 
9606 static tree
lookup_template_class_1(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)9607 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9608 			 int entering_scope, tsubst_flags_t complain)
9609 {
9610   tree templ = NULL_TREE, parmlist;
9611   tree t;
9612   spec_entry **slot;
9613   spec_entry *entry;
9614   spec_entry elt;
9615   hashval_t hash;
9616 
9617   if (identifier_p (d1))
9618     {
9619       tree value = innermost_non_namespace_value (d1);
9620       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9621 	templ = value;
9622       else
9623 	{
9624 	  if (context)
9625 	    push_decl_namespace (context);
9626 	  templ = lookup_name (d1);
9627 	  templ = maybe_get_template_decl_from_type_decl (templ);
9628 	  if (context)
9629 	    pop_decl_namespace ();
9630 	}
9631       if (templ)
9632 	context = DECL_CONTEXT (templ);
9633     }
9634   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9635     {
9636       tree type = TREE_TYPE (d1);
9637 
9638       /* If we are declaring a constructor, say A<T>::A<T>, we will get
9639 	 an implicit typename for the second A.  Deal with it.  */
9640       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9641 	type = TREE_TYPE (type);
9642 
9643       if (CLASSTYPE_TEMPLATE_INFO (type))
9644 	{
9645 	  templ = CLASSTYPE_TI_TEMPLATE (type);
9646 	  d1 = DECL_NAME (templ);
9647 	}
9648     }
9649   else if (TREE_CODE (d1) == ENUMERAL_TYPE
9650 	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9651     {
9652       templ = TYPE_TI_TEMPLATE (d1);
9653       d1 = DECL_NAME (templ);
9654     }
9655   else if (DECL_TYPE_TEMPLATE_P (d1))
9656     {
9657       templ = d1;
9658       d1 = DECL_NAME (templ);
9659       context = DECL_CONTEXT (templ);
9660     }
9661   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9662     {
9663       templ = d1;
9664       d1 = DECL_NAME (templ);
9665     }
9666 
9667   /* Issue an error message if we didn't find a template.  */
9668   if (! templ)
9669     {
9670       if (complain & tf_error)
9671 	error ("%qT is not a template", d1);
9672       return error_mark_node;
9673     }
9674 
9675   if (TREE_CODE (templ) != TEMPLATE_DECL
9676 	 /* Make sure it's a user visible template, if it was named by
9677 	    the user.  */
9678       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9679 	  && !PRIMARY_TEMPLATE_P (templ)))
9680     {
9681       if (complain & tf_error)
9682 	{
9683 	  error ("non-template type %qT used as a template", d1);
9684 	  if (in_decl)
9685 	    error ("for template declaration %q+D", in_decl);
9686 	}
9687       return error_mark_node;
9688     }
9689 
9690   complain &= ~tf_user;
9691 
9692   /* An alias that just changes the name of a template is equivalent to the
9693      other template, so if any of the arguments are pack expansions, strip
9694      the alias to avoid problems with a pack expansion passed to a non-pack
9695      alias template parameter (DR 1430).  */
9696   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9697     templ = get_underlying_template (templ);
9698 
9699   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9700     {
9701       tree parm;
9702       tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9703       if (arglist2 == error_mark_node
9704 	  || (!uses_template_parms (arglist2)
9705 	      && check_instantiated_args (templ, arglist2, complain)))
9706 	return error_mark_node;
9707 
9708       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9709       return parm;
9710     }
9711   else
9712     {
9713       tree template_type = TREE_TYPE (templ);
9714       tree gen_tmpl;
9715       tree type_decl;
9716       tree found = NULL_TREE;
9717       int arg_depth;
9718       int parm_depth;
9719       int is_dependent_type;
9720       int use_partial_inst_tmpl = false;
9721 
9722       if (template_type == error_mark_node)
9723 	/* An error occurred while building the template TEMPL, and a
9724 	   diagnostic has most certainly been emitted for that
9725 	   already.  Let's propagate that error.  */
9726 	return error_mark_node;
9727 
9728       gen_tmpl = most_general_template (templ);
9729       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9730       parm_depth = TMPL_PARMS_DEPTH (parmlist);
9731       arg_depth = TMPL_ARGS_DEPTH (arglist);
9732 
9733       if (arg_depth == 1 && parm_depth > 1)
9734 	{
9735 	  /* We've been given an incomplete set of template arguments.
9736 	     For example, given:
9737 
9738 	       template <class T> struct S1 {
9739 		 template <class U> struct S2 {};
9740 		 template <class U> struct S2<U*> {};
9741 		};
9742 
9743 	     we will be called with an ARGLIST of `U*', but the
9744 	     TEMPLATE will be `template <class T> template
9745 	     <class U> struct S1<T>::S2'.  We must fill in the missing
9746 	     arguments.  */
9747 	  tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9748 	  arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9749 	  arg_depth = TMPL_ARGS_DEPTH (arglist);
9750 	}
9751 
9752       /* Now we should have enough arguments.  */
9753       gcc_assert (parm_depth == arg_depth);
9754 
9755       /* From here on, we're only interested in the most general
9756 	 template.  */
9757 
9758       /* Calculate the BOUND_ARGS.  These will be the args that are
9759 	 actually tsubst'd into the definition to create the
9760 	 instantiation.  */
9761       arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
9762 						 complain,
9763 						 /*require_all_args=*/true,
9764 						 /*use_default_args=*/true);
9765 
9766       if (arglist == error_mark_node)
9767 	/* We were unable to bind the arguments.  */
9768 	return error_mark_node;
9769 
9770       /* In the scope of a template class, explicit references to the
9771 	 template class refer to the type of the template, not any
9772 	 instantiation of it.  For example, in:
9773 
9774 	   template <class T> class C { void f(C<T>); }
9775 
9776 	 the `C<T>' is just the same as `C'.  Outside of the
9777 	 class, however, such a reference is an instantiation.  */
9778       if (entering_scope
9779 	  || !PRIMARY_TEMPLATE_P (gen_tmpl)
9780 	  || currently_open_class (template_type))
9781 	{
9782 	  tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9783 
9784 	  if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9785 	    return template_type;
9786 	}
9787 
9788       /* If we already have this specialization, return it.  */
9789       elt.tmpl = gen_tmpl;
9790       elt.args = arglist;
9791       elt.spec = NULL_TREE;
9792       hash = spec_hasher::hash (&elt);
9793       entry = type_specializations->find_with_hash (&elt, hash);
9794 
9795       if (entry)
9796 	return entry->spec;
9797 
9798       /* If the template's constraints are not satisfied,
9799          then we cannot form a valid type.
9800 
9801          Note that the check is deferred until after the hash
9802          lookup. This prevents redundant checks on previously
9803          instantiated specializations. */
9804       if (flag_concepts
9805 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl)
9806 	  && !constraints_satisfied_p (gen_tmpl, arglist))
9807         {
9808           if (complain & tf_error)
9809             {
9810 	      auto_diagnostic_group d;
9811               error ("template constraint failure for %qD", gen_tmpl);
9812               diagnose_constraints (input_location, gen_tmpl, arglist);
9813             }
9814           return error_mark_node;
9815         }
9816 
9817       is_dependent_type = uses_template_parms (arglist);
9818 
9819       /* If the deduced arguments are invalid, then the binding
9820 	 failed.  */
9821       if (!is_dependent_type
9822 	  && check_instantiated_args (gen_tmpl,
9823 				      INNERMOST_TEMPLATE_ARGS (arglist),
9824 				      complain))
9825 	return error_mark_node;
9826 
9827       if (!is_dependent_type
9828 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
9829 	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9830 	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9831 	{
9832 	  found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
9833 				      DECL_NAME (gen_tmpl),
9834 				      /*tag_scope=*/ts_global);
9835 	  return found;
9836 	}
9837 
9838       context = DECL_CONTEXT (gen_tmpl);
9839       if (context && TYPE_P (context))
9840 	{
9841 	  context = tsubst_aggr_type (context, arglist, complain, in_decl, true);
9842 	  context = complete_type (context);
9843 	}
9844       else
9845 	context = tsubst (context, arglist, complain, in_decl);
9846 
9847       if (context == error_mark_node)
9848 	return error_mark_node;
9849 
9850       if (!context)
9851 	context = global_namespace;
9852 
9853       /* Create the type.  */
9854       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9855 	{
9856 	  /* The user referred to a specialization of an alias
9857 	    template represented by GEN_TMPL.
9858 
9859 	    [temp.alias]/2 says:
9860 
9861 	        When a template-id refers to the specialization of an
9862 		alias template, it is equivalent to the associated
9863 		type obtained by substitution of its
9864 		template-arguments for the template-parameters in the
9865 		type-id of the alias template.  */
9866 
9867 	  t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
9868 	  /* Note that the call above (by indirectly calling
9869 	     register_specialization in tsubst_decl) registers the
9870 	     TYPE_DECL representing the specialization of the alias
9871 	     template.  So next time someone substitutes ARGLIST for
9872 	     the template parms into the alias template (GEN_TMPL),
9873 	     she'll get that TYPE_DECL back.  */
9874 
9875 	  if (t == error_mark_node)
9876 	    return t;
9877 	}
9878       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
9879 	{
9880 	  if (!is_dependent_type)
9881 	    {
9882 	      set_current_access_from_decl (TYPE_NAME (template_type));
9883 	      t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
9884 			      tsubst (ENUM_UNDERLYING_TYPE (template_type),
9885 				      arglist, complain, in_decl),
9886 			      tsubst_attributes (TYPE_ATTRIBUTES (template_type),
9887 						 arglist, complain, in_decl),
9888 			      SCOPED_ENUM_P (template_type), NULL);
9889 
9890 	      if (t == error_mark_node)
9891 		return t;
9892 	    }
9893 	  else
9894             {
9895               /* We don't want to call start_enum for this type, since
9896                  the values for the enumeration constants may involve
9897                  template parameters.  And, no one should be interested
9898                  in the enumeration constants for such a type.  */
9899               t = cxx_make_type (ENUMERAL_TYPE);
9900               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
9901             }
9902           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
9903 	  ENUM_FIXED_UNDERLYING_TYPE_P (t)
9904 	    = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
9905 	}
9906       else if (CLASS_TYPE_P (template_type))
9907 	{
9908 	  /* Lambda closures are regenerated in tsubst_lambda_expr, not
9909 	     instantiated here.  */
9910 	  gcc_assert (!LAMBDA_TYPE_P (template_type));
9911 
9912 	  t = make_class_type (TREE_CODE (template_type));
9913 	  CLASSTYPE_DECLARED_CLASS (t)
9914 	    = CLASSTYPE_DECLARED_CLASS (template_type);
9915 	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
9916 
9917 	  /* A local class.  Make sure the decl gets registered properly.  */
9918 	  if (context == current_function_decl)
9919 	    if (pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current)
9920 		== error_mark_node)
9921 	      return error_mark_node;
9922 
9923 	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
9924 	    /* This instantiation is another name for the primary
9925 	       template type. Set the TYPE_CANONICAL field
9926 	       appropriately. */
9927 	    TYPE_CANONICAL (t) = template_type;
9928 	  else if (any_template_arguments_need_structural_equality_p (arglist))
9929 	    /* Some of the template arguments require structural
9930 	       equality testing, so this template class requires
9931 	       structural equality testing. */
9932 	    SET_TYPE_STRUCTURAL_EQUALITY (t);
9933 	}
9934       else
9935 	gcc_unreachable ();
9936 
9937       /* If we called start_enum or pushtag above, this information
9938 	 will already be set up.  */
9939       if (!TYPE_NAME (t))
9940 	{
9941 	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
9942 
9943 	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
9944 	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
9945 	  DECL_SOURCE_LOCATION (type_decl)
9946 	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
9947 	}
9948       else
9949 	type_decl = TYPE_NAME (t);
9950 
9951       if (CLASS_TYPE_P (template_type))
9952 	{
9953 	  TREE_PRIVATE (type_decl)
9954 	    = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
9955 	  TREE_PROTECTED (type_decl)
9956 	    = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
9957 	  if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
9958 	    {
9959 	      DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
9960 	      DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
9961 	    }
9962 	}
9963 
9964       if (OVERLOAD_TYPE_P (t)
9965 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9966 	{
9967 	  static const char *tags[] = {"abi_tag", "may_alias"};
9968 
9969 	  for (unsigned ix = 0; ix != 2; ix++)
9970 	    {
9971 	      tree attributes
9972 		= lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
9973 
9974 	      if (attributes)
9975 		TYPE_ATTRIBUTES (t)
9976 		  = tree_cons (TREE_PURPOSE (attributes),
9977 			       TREE_VALUE (attributes),
9978 			       TYPE_ATTRIBUTES (t));
9979 	    }
9980 	}
9981 
9982       /* Let's consider the explicit specialization of a member
9983          of a class template specialization that is implicitly instantiated,
9984 	 e.g.:
9985 	     template<class T>
9986 	     struct S
9987 	     {
9988 	       template<class U> struct M {}; //#0
9989 	     };
9990 
9991 	     template<>
9992 	     template<>
9993 	     struct S<int>::M<char> //#1
9994 	     {
9995 	       int i;
9996 	     };
9997 	[temp.expl.spec]/4 says this is valid.
9998 
9999 	In this case, when we write:
10000 	S<int>::M<char> m;
10001 
10002 	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
10003 	the one of #0.
10004 
10005 	When we encounter #1, we want to store the partial instantiation
10006 	of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
10007 
10008 	For all cases other than this "explicit specialization of member of a
10009 	class template", we just want to store the most general template into
10010 	the CLASSTYPE_TI_TEMPLATE of M.
10011 
10012 	This case of "explicit specialization of member of a class template"
10013 	only happens when:
10014 	1/ the enclosing class is an instantiation of, and therefore not
10015 	the same as, the context of the most general template, and
10016 	2/ we aren't looking at the partial instantiation itself, i.e.
10017 	the innermost arguments are not the same as the innermost parms of
10018 	the most general template.
10019 
10020 	So it's only when 1/ and 2/ happens that we want to use the partial
10021 	instantiation of the member template in lieu of its most general
10022 	template.  */
10023 
10024       if (PRIMARY_TEMPLATE_P (gen_tmpl)
10025 	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
10026 	  /* the enclosing class must be an instantiation...  */
10027 	  && CLASS_TYPE_P (context)
10028 	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
10029 	{
10030 	  TREE_VEC_LENGTH (arglist)--;
10031 	  ++processing_template_decl;
10032 	  tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
10033 	  tree partial_inst_args =
10034 	    tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
10035 		    arglist, complain, NULL_TREE);
10036 	  --processing_template_decl;
10037 	  TREE_VEC_LENGTH (arglist)++;
10038 	  if (partial_inst_args == error_mark_node)
10039 	    return error_mark_node;
10040 	  use_partial_inst_tmpl =
10041 	    /*...and we must not be looking at the partial instantiation
10042 	     itself. */
10043 	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
10044 				 partial_inst_args);
10045 	}
10046 
10047       if (!use_partial_inst_tmpl)
10048 	/* This case is easy; there are no member templates involved.  */
10049 	found = gen_tmpl;
10050       else
10051 	{
10052 	  /* This is a full instantiation of a member template.  Find
10053 	     the partial instantiation of which this is an instance.  */
10054 
10055 	  /* Temporarily reduce by one the number of levels in the ARGLIST
10056 	     so as to avoid comparing the last set of arguments.  */
10057 	  TREE_VEC_LENGTH (arglist)--;
10058 	  /* We don't use COMPLAIN in the following call because this isn't
10059 	     the immediate context of deduction.  For instance, tf_partial
10060 	     could be set here as we might be at the beginning of template
10061 	     argument deduction when any explicitly specified template
10062 	     arguments are substituted into the function type.  tf_partial
10063 	     could lead into trouble because we wouldn't find the partial
10064 	     instantiation that might have been created outside tf_partial
10065 	     context, because the levels of template parameters wouldn't
10066 	     match, because in a tf_partial context, tsubst doesn't reduce
10067 	     TEMPLATE_PARM_LEVEL.  */
10068 	  found = tsubst (gen_tmpl, arglist, tf_none, NULL_TREE);
10069 	  TREE_VEC_LENGTH (arglist)++;
10070 	  /* FOUND is either a proper class type, or an alias
10071 	     template specialization.  In the later case, it's a
10072 	     TYPE_DECL, resulting from the substituting of arguments
10073 	     for parameters in the TYPE_DECL of the alias template
10074 	     done earlier.  So be careful while getting the template
10075 	     of FOUND.  */
10076 	  found = (TREE_CODE (found) == TEMPLATE_DECL
10077 		   ? found
10078 		   : (TREE_CODE (found) == TYPE_DECL
10079 		      ? DECL_TI_TEMPLATE (found)
10080 		      : CLASSTYPE_TI_TEMPLATE (found)));
10081 
10082 	  if (DECL_CLASS_TEMPLATE_P (found)
10083 	      && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (found)))
10084 	    {
10085 	      /* If this partial instantiation is specialized, we want to
10086 		 use it for hash table lookup.  */
10087 	      elt.tmpl = found;
10088 	      elt.args = arglist = INNERMOST_TEMPLATE_ARGS (arglist);
10089 	      hash = spec_hasher::hash (&elt);
10090 	    }
10091 	}
10092 
10093       // Build template info for the new specialization.
10094       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
10095 
10096       elt.spec = t;
10097       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
10098       gcc_checking_assert (*slot == NULL);
10099       entry = ggc_alloc<spec_entry> ();
10100       *entry = elt;
10101       *slot = entry;
10102 
10103       /* Note this use of the partial instantiation so we can check it
10104 	 later in maybe_process_partial_specialization.  */
10105       DECL_TEMPLATE_INSTANTIATIONS (found)
10106 	= tree_cons (arglist, t,
10107 		     DECL_TEMPLATE_INSTANTIATIONS (found));
10108 
10109       if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
10110 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
10111 	/* Now that the type has been registered on the instantiations
10112 	   list, we set up the enumerators.  Because the enumeration
10113 	   constants may involve the enumeration type itself, we make
10114 	   sure to register the type first, and then create the
10115 	   constants.  That way, doing tsubst_expr for the enumeration
10116 	   constants won't result in recursive calls here; we'll find
10117 	   the instantiation and exit above.  */
10118 	tsubst_enum (template_type, t, arglist);
10119 
10120       if (CLASS_TYPE_P (template_type) && is_dependent_type)
10121 	/* If the type makes use of template parameters, the
10122 	   code that generates debugging information will crash.  */
10123 	DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
10124 
10125       /* Possibly limit visibility based on template args.  */
10126       TREE_PUBLIC (type_decl) = 1;
10127       determine_visibility (type_decl);
10128 
10129       inherit_targ_abi_tags (t);
10130 
10131       return t;
10132     }
10133 }
10134 
10135 /* Wrapper for lookup_template_class_1.  */
10136 
10137 tree
lookup_template_class(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)10138 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
10139                        int entering_scope, tsubst_flags_t complain)
10140 {
10141   tree ret;
10142   timevar_push (TV_TEMPLATE_INST);
10143   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
10144                                  entering_scope, complain);
10145   timevar_pop (TV_TEMPLATE_INST);
10146   return ret;
10147 }
10148 
10149 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
10150 
10151 tree
lookup_template_variable(tree templ,tree arglist)10152 lookup_template_variable (tree templ, tree arglist)
10153 {
10154   if (flag_concepts && variable_concept_p (templ))
10155     return build_concept_check (templ, arglist, tf_none);
10156 
10157   /* The type of the expression is NULL_TREE since the template-id could refer
10158      to an explicit or partial specialization. */
10159   return build2 (TEMPLATE_ID_EXPR, NULL_TREE, templ, arglist);
10160 }
10161 
10162 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
10163 
10164 tree
finish_template_variable(tree var,tsubst_flags_t complain)10165 finish_template_variable (tree var, tsubst_flags_t complain)
10166 {
10167   tree templ = TREE_OPERAND (var, 0);
10168   tree arglist = TREE_OPERAND (var, 1);
10169 
10170   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
10171   arglist = add_outermost_template_args (tmpl_args, arglist);
10172 
10173   templ = most_general_template (templ);
10174   tree parms = DECL_TEMPLATE_PARMS (templ);
10175   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
10176 					     /*req_all*/true,
10177 					     /*use_default*/true);
10178 
10179   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
10180     {
10181       if (complain & tf_error)
10182 	{
10183 	  auto_diagnostic_group d;
10184 	  error ("use of invalid variable template %qE", var);
10185 	  diagnose_constraints (location_of (var), templ, arglist);
10186 	}
10187       return error_mark_node;
10188     }
10189 
10190   return instantiate_template (templ, arglist, complain);
10191 }
10192 
10193 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
10194    TARGS template args, and instantiate it if it's not dependent.  */
10195 
10196 tree
lookup_and_finish_template_variable(tree templ,tree targs,tsubst_flags_t complain)10197 lookup_and_finish_template_variable (tree templ, tree targs,
10198 				     tsubst_flags_t complain)
10199 {
10200   templ = lookup_template_variable (templ, targs);
10201   if (!any_dependent_template_arguments_p (targs))
10202     {
10203       templ = finish_template_variable (templ, complain);
10204       mark_used (templ);
10205     }
10206 
10207   return convert_from_reference (templ);
10208 }
10209 
10210 
10211 struct pair_fn_data
10212 {
10213   tree_fn_t fn;
10214   tree_fn_t any_fn;
10215   void *data;
10216   /* True when we should also visit template parameters that occur in
10217      non-deduced contexts.  */
10218   bool include_nondeduced_p;
10219   hash_set<tree> *visited;
10220 };
10221 
10222 /* Called from for_each_template_parm via walk_tree.  */
10223 
10224 static tree
for_each_template_parm_r(tree * tp,int * walk_subtrees,void * d)10225 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
10226 {
10227   tree t = *tp;
10228   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
10229   tree_fn_t fn = pfd->fn;
10230   void *data = pfd->data;
10231   tree result = NULL_TREE;
10232 
10233 #define WALK_SUBTREE(NODE)						\
10234   do									\
10235     {									\
10236       result = for_each_template_parm (NODE, fn, data, pfd->visited,	\
10237 				       pfd->include_nondeduced_p,	\
10238 				       pfd->any_fn);			\
10239       if (result) goto out;						\
10240     }									\
10241   while (0)
10242 
10243   if (pfd->any_fn && (*pfd->any_fn)(t, data))
10244     return t;
10245 
10246   if (TYPE_P (t)
10247       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
10248     WALK_SUBTREE (TYPE_CONTEXT (t));
10249 
10250   switch (TREE_CODE (t))
10251     {
10252     case RECORD_TYPE:
10253       if (TYPE_PTRMEMFUNC_P (t))
10254 	break;
10255       /* Fall through.  */
10256 
10257     case UNION_TYPE:
10258     case ENUMERAL_TYPE:
10259       if (!TYPE_TEMPLATE_INFO (t))
10260 	*walk_subtrees = 0;
10261       else
10262 	WALK_SUBTREE (TYPE_TI_ARGS (t));
10263       break;
10264 
10265     case INTEGER_TYPE:
10266       WALK_SUBTREE (TYPE_MIN_VALUE (t));
10267       WALK_SUBTREE (TYPE_MAX_VALUE (t));
10268       break;
10269 
10270     case METHOD_TYPE:
10271       /* Since we're not going to walk subtrees, we have to do this
10272 	 explicitly here.  */
10273       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
10274       /* Fall through.  */
10275 
10276     case FUNCTION_TYPE:
10277       /* Check the return type.  */
10278       WALK_SUBTREE (TREE_TYPE (t));
10279 
10280       /* Check the parameter types.  Since default arguments are not
10281 	 instantiated until they are needed, the TYPE_ARG_TYPES may
10282 	 contain expressions that involve template parameters.  But,
10283 	 no-one should be looking at them yet.  And, once they're
10284 	 instantiated, they don't contain template parameters, so
10285 	 there's no point in looking at them then, either.  */
10286       {
10287 	tree parm;
10288 
10289 	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
10290 	  WALK_SUBTREE (TREE_VALUE (parm));
10291 
10292 	/* Since we've already handled the TYPE_ARG_TYPES, we don't
10293 	   want walk_tree walking into them itself.  */
10294 	*walk_subtrees = 0;
10295       }
10296 
10297       if (flag_noexcept_type)
10298 	{
10299 	  tree spec = TYPE_RAISES_EXCEPTIONS (t);
10300 	  if (spec)
10301 	    WALK_SUBTREE (TREE_PURPOSE (spec));
10302 	}
10303       break;
10304 
10305     case TYPEOF_TYPE:
10306     case DECLTYPE_TYPE:
10307     case UNDERLYING_TYPE:
10308       if (pfd->include_nondeduced_p
10309 	  && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
10310 				     pfd->visited,
10311 				     pfd->include_nondeduced_p,
10312 				     pfd->any_fn))
10313 	return error_mark_node;
10314       *walk_subtrees = false;
10315       break;
10316 
10317     case FUNCTION_DECL:
10318     case VAR_DECL:
10319       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10320 	WALK_SUBTREE (DECL_TI_ARGS (t));
10321       /* Fall through.  */
10322 
10323     case PARM_DECL:
10324     case CONST_DECL:
10325       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
10326 	WALK_SUBTREE (DECL_INITIAL (t));
10327       if (DECL_CONTEXT (t)
10328 	  && pfd->include_nondeduced_p)
10329 	WALK_SUBTREE (DECL_CONTEXT (t));
10330       break;
10331 
10332     case BOUND_TEMPLATE_TEMPLATE_PARM:
10333       /* Record template parameters such as `T' inside `TT<T>'.  */
10334       WALK_SUBTREE (TYPE_TI_ARGS (t));
10335       /* Fall through.  */
10336 
10337     case TEMPLATE_TEMPLATE_PARM:
10338     case TEMPLATE_TYPE_PARM:
10339     case TEMPLATE_PARM_INDEX:
10340       if (fn && (*fn)(t, data))
10341 	return t;
10342       else if (!fn)
10343 	return t;
10344       break;
10345 
10346     case TEMPLATE_DECL:
10347       /* A template template parameter is encountered.  */
10348       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10349 	WALK_SUBTREE (TREE_TYPE (t));
10350 
10351       /* Already substituted template template parameter */
10352       *walk_subtrees = 0;
10353       break;
10354 
10355     case TYPENAME_TYPE:
10356       /* A template-id in a TYPENAME_TYPE might be a deduced context after
10357 	 partial instantiation.  */
10358       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
10359       break;
10360 
10361     case CONSTRUCTOR:
10362       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
10363 	  && pfd->include_nondeduced_p)
10364 	WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
10365       break;
10366 
10367     case INDIRECT_REF:
10368     case COMPONENT_REF:
10369       /* If there's no type, then this thing must be some expression
10370 	 involving template parameters.  */
10371       if (!fn && !TREE_TYPE (t))
10372 	return error_mark_node;
10373       break;
10374 
10375     case MODOP_EXPR:
10376     case CAST_EXPR:
10377     case IMPLICIT_CONV_EXPR:
10378     case REINTERPRET_CAST_EXPR:
10379     case CONST_CAST_EXPR:
10380     case STATIC_CAST_EXPR:
10381     case DYNAMIC_CAST_EXPR:
10382     case ARROW_EXPR:
10383     case DOTSTAR_EXPR:
10384     case TYPEID_EXPR:
10385     case PSEUDO_DTOR_EXPR:
10386       if (!fn)
10387 	return error_mark_node;
10388       break;
10389 
10390     case SCOPE_REF:
10391       if (pfd->include_nondeduced_p)
10392 	WALK_SUBTREE (TREE_OPERAND (t, 0));
10393       break;
10394 
10395     case REQUIRES_EXPR:
10396       {
10397 	if (!fn)
10398 	  return error_mark_node;
10399 
10400 	/* Recursively walk the type of each constraint variable.  */
10401 	tree p = TREE_OPERAND (t, 0);
10402 	while (p)
10403 	  {
10404 	    WALK_SUBTREE (TREE_TYPE (p));
10405 	    p = TREE_CHAIN (p);
10406 	  }
10407       }
10408       break;
10409 
10410     default:
10411       break;
10412     }
10413 
10414   #undef WALK_SUBTREE
10415 
10416   /* We didn't find any template parameters we liked.  */
10417  out:
10418   return result;
10419 }
10420 
10421 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
10422    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
10423    call FN with the parameter and the DATA.
10424    If FN returns nonzero, the iteration is terminated, and
10425    for_each_template_parm returns 1.  Otherwise, the iteration
10426    continues.  If FN never returns a nonzero value, the value
10427    returned by for_each_template_parm is 0.  If FN is NULL, it is
10428    considered to be the function which always returns 1.
10429 
10430    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
10431    parameters that occur in non-deduced contexts.  When false, only
10432    visits those template parameters that can be deduced.  */
10433 
10434 static tree
for_each_template_parm(tree t,tree_fn_t fn,void * data,hash_set<tree> * visited,bool include_nondeduced_p,tree_fn_t any_fn)10435 for_each_template_parm (tree t, tree_fn_t fn, void* data,
10436 			hash_set<tree> *visited,
10437 			bool include_nondeduced_p,
10438 			tree_fn_t any_fn)
10439 {
10440   struct pair_fn_data pfd;
10441   tree result;
10442 
10443   /* Set up.  */
10444   pfd.fn = fn;
10445   pfd.any_fn = any_fn;
10446   pfd.data = data;
10447   pfd.include_nondeduced_p = include_nondeduced_p;
10448 
10449   /* Walk the tree.  (Conceptually, we would like to walk without
10450      duplicates, but for_each_template_parm_r recursively calls
10451      for_each_template_parm, so we would need to reorganize a fair
10452      bit to use walk_tree_without_duplicates, so we keep our own
10453      visited list.)  */
10454   if (visited)
10455     pfd.visited = visited;
10456   else
10457     pfd.visited = new hash_set<tree>;
10458   result = cp_walk_tree (&t,
10459 		         for_each_template_parm_r,
10460 		         &pfd,
10461 		         pfd.visited);
10462 
10463   /* Clean up.  */
10464   if (!visited)
10465     {
10466       delete pfd.visited;
10467       pfd.visited = 0;
10468     }
10469 
10470   return result;
10471 }
10472 
10473 struct find_template_parameter_info
10474 {
find_template_parameter_infofind_template_parameter_info10475   explicit find_template_parameter_info (tree ctx_parms)
10476     : parm_list (NULL_TREE),
10477       ctx_parms (ctx_parms),
10478       max_depth (TMPL_PARMS_DEPTH (ctx_parms))
10479   {}
10480 
10481   hash_set<tree> visited;
10482   hash_set<tree> parms;
10483   tree parm_list;
10484   tree ctx_parms;
10485   int max_depth;
10486 };
10487 
10488 /* Appends the declaration of T to the list in DATA.  */
10489 
10490 static int
keep_template_parm(tree t,void * data)10491 keep_template_parm (tree t, void* data)
10492 {
10493   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10494 
10495   /* Template parameters declared within the expression are not part of
10496      the parameter mapping. For example, in this concept:
10497 
10498        template<typename T>
10499        concept C = requires { <expr> } -> same_as<int>;
10500 
10501      the return specifier same_as<int> declares a new decltype parameter
10502      that must not be part of the parameter mapping. The same is true
10503      for generic lambda parameters, lambda template parameters, etc.  */
10504   int level;
10505   int index;
10506   template_parm_level_and_index (t, &level, &index);
10507   if (level > ftpi->max_depth)
10508     return 0;
10509 
10510   if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10511     /* We want the underlying TEMPLATE_TEMPLATE_PARM, not the
10512        BOUND_TEMPLATE_TEMPLATE_PARM itself.  */
10513     t = TREE_TYPE (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (t));
10514 
10515   /* Arguments like const T yield parameters like const T. This means that
10516      a template-id like X<T, const T> would yield two distinct parameters:
10517      T and const T. Adjust types to their unqualified versions.  */
10518   if (TYPE_P (t))
10519     t = TYPE_MAIN_VARIANT (t);
10520   if (!ftpi->parms.add (t))
10521     ftpi->parm_list = tree_cons (NULL_TREE, t, ftpi->parm_list);
10522 
10523   return 0;
10524 }
10525 
10526 /* Ensure that we recursively examine certain terms that are not normally
10527    visited in for_each_template_parm_r.  */
10528 
10529 static int
any_template_parm_r(tree t,void * data)10530 any_template_parm_r (tree t, void *data)
10531 {
10532   find_template_parameter_info *ftpi = (find_template_parameter_info*)data;
10533 
10534 #define WALK_SUBTREE(NODE)						\
10535   do									\
10536     {									\
10537       for_each_template_parm (NODE, keep_template_parm, data,		\
10538 			      &ftpi->visited, true,			\
10539 			      any_template_parm_r);			\
10540     }									\
10541   while (0)
10542 
10543   /* A mention of a member alias/typedef is a use of all of its template
10544      arguments, including those from the enclosing class, so we don't use
10545      alias_template_specialization_p here.  */
10546   if (TYPE_P (t) && typedef_variant_p (t))
10547     if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
10548       WALK_SUBTREE (TI_ARGS (tinfo));
10549 
10550   switch (TREE_CODE (t))
10551     {
10552     case TEMPLATE_TYPE_PARM:
10553       /* Type constraints of a placeholder type may contain parameters.  */
10554       if (is_auto (t))
10555 	if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
10556 	  WALK_SUBTREE (constr);
10557       break;
10558 
10559     case TEMPLATE_ID_EXPR:
10560       /* Search through references to variable templates.  */
10561       WALK_SUBTREE (TREE_OPERAND (t, 0));
10562       WALK_SUBTREE (TREE_OPERAND (t, 1));
10563       break;
10564 
10565     case TEMPLATE_PARM_INDEX:
10566     case PARM_DECL:
10567       /* A parameter or constraint variable may also depend on a template
10568 	 parameter without explicitly naming it.  */
10569       WALK_SUBTREE (TREE_TYPE (t));
10570       break;
10571 
10572     case TEMPLATE_DECL:
10573       {
10574 	/* If T is a member template that shares template parameters with
10575 	   ctx_parms, we need to mark all those parameters for mapping.  */
10576 	tree dparms = DECL_TEMPLATE_PARMS (t);
10577 	tree cparms = ftpi->ctx_parms;
10578 	while (TMPL_PARMS_DEPTH (dparms) > ftpi->max_depth)
10579 	  dparms = TREE_CHAIN (dparms);
10580 	while (TMPL_PARMS_DEPTH (cparms) > TMPL_PARMS_DEPTH (dparms))
10581 	  cparms = TREE_CHAIN (cparms);
10582 	while (dparms
10583 	       && (TREE_TYPE (TREE_VALUE (dparms))
10584 		   != TREE_TYPE (TREE_VALUE (cparms))))
10585 	  dparms = TREE_CHAIN (dparms),
10586 	    cparms = TREE_CHAIN (cparms);
10587 	if (dparms)
10588 	  {
10589 	    int ddepth = TMPL_PARMS_DEPTH (dparms);
10590 	    tree dargs = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (t)));
10591 	    for (int i = 0; i < ddepth; ++i)
10592 	      WALK_SUBTREE (TMPL_ARGS_LEVEL (dargs, i+1));
10593 	  }
10594       }
10595       break;
10596 
10597     case LAMBDA_EXPR:
10598       {
10599 	/* Look in the parms and body.  */
10600 	tree fn = lambda_function (t);
10601 	WALK_SUBTREE (TREE_TYPE (fn));
10602 	WALK_SUBTREE (DECL_SAVED_TREE (fn));
10603       }
10604       break;
10605 
10606     case IDENTIFIER_NODE:
10607       if (IDENTIFIER_CONV_OP_P (t))
10608 	/* The conversion-type-id of a conversion operator may be dependent.  */
10609 	WALK_SUBTREE (TREE_TYPE (t));
10610       break;
10611 
10612     default:
10613       break;
10614     }
10615 
10616   /* Keep walking.  */
10617   return 0;
10618 }
10619 
10620 /* Returns a list of unique template parameters found within T, where CTX_PARMS
10621    are the template parameters in scope.  */
10622 
10623 tree
find_template_parameters(tree t,tree ctx_parms)10624 find_template_parameters (tree t, tree ctx_parms)
10625 {
10626   if (!ctx_parms)
10627     return NULL_TREE;
10628 
10629   find_template_parameter_info ftpi (ctx_parms);
10630   for_each_template_parm (t, keep_template_parm, &ftpi, &ftpi.visited,
10631 			  /*include_nondeduced*/true, any_template_parm_r);
10632   return ftpi.parm_list;
10633 }
10634 
10635 /* Returns true if T depends on any template parameter.  */
10636 
10637 int
uses_template_parms(tree t)10638 uses_template_parms (tree t)
10639 {
10640   if (t == NULL_TREE)
10641     return false;
10642 
10643   bool dependent_p;
10644   int saved_processing_template_decl;
10645 
10646   saved_processing_template_decl = processing_template_decl;
10647   if (!saved_processing_template_decl)
10648     processing_template_decl = 1;
10649   if (TYPE_P (t))
10650     dependent_p = dependent_type_p (t);
10651   else if (TREE_CODE (t) == TREE_VEC)
10652     dependent_p = any_dependent_template_arguments_p (t);
10653   else if (TREE_CODE (t) == TREE_LIST)
10654     dependent_p = (uses_template_parms (TREE_VALUE (t))
10655 		   || uses_template_parms (TREE_CHAIN (t)));
10656   else if (TREE_CODE (t) == TYPE_DECL)
10657     dependent_p = dependent_type_p (TREE_TYPE (t));
10658   else if (t == error_mark_node)
10659     dependent_p = false;
10660   else
10661     dependent_p = value_dependent_expression_p (t);
10662 
10663   processing_template_decl = saved_processing_template_decl;
10664 
10665   return dependent_p;
10666 }
10667 
10668 /* Returns true iff current_function_decl is an incompletely instantiated
10669    template.  Useful instead of processing_template_decl because the latter
10670    is set to 0 during instantiate_non_dependent_expr.  */
10671 
10672 bool
in_template_function(void)10673 in_template_function (void)
10674 {
10675   tree fn = current_function_decl;
10676   bool ret;
10677   ++processing_template_decl;
10678   ret = (fn && DECL_LANG_SPECIFIC (fn)
10679 	 && DECL_TEMPLATE_INFO (fn)
10680 	 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10681   --processing_template_decl;
10682   return ret;
10683 }
10684 
10685 /* Returns true if T depends on any template parameter with level LEVEL.  */
10686 
10687 bool
uses_template_parms_level(tree t,int level)10688 uses_template_parms_level (tree t, int level)
10689 {
10690   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10691 				 /*include_nondeduced_p=*/true);
10692 }
10693 
10694 /* Returns true if the signature of DECL depends on any template parameter from
10695    its enclosing class.  */
10696 
10697 bool
uses_outer_template_parms(tree decl)10698 uses_outer_template_parms (tree decl)
10699 {
10700   int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10701   if (depth == 0)
10702     return false;
10703   if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10704 			      &depth, NULL, /*include_nondeduced_p=*/true))
10705     return true;
10706   if (PRIMARY_TEMPLATE_P (decl)
10707       && for_each_template_parm (INNERMOST_TEMPLATE_PARMS
10708 				 (DECL_TEMPLATE_PARMS (decl)),
10709 				 template_parm_outer_level,
10710 				 &depth, NULL, /*include_nondeduced_p=*/true))
10711     return true;
10712   tree ci = get_constraints (decl);
10713   if (ci)
10714     ci = CI_ASSOCIATED_CONSTRAINTS (ci);
10715   if (ci && for_each_template_parm (ci, template_parm_outer_level,
10716 				    &depth, NULL, /*nondeduced*/true))
10717     return true;
10718   return false;
10719 }
10720 
10721 /* Returns TRUE iff INST is an instantiation we don't need to do in an
10722    ill-formed translation unit, i.e. a variable or function that isn't
10723    usable in a constant expression.  */
10724 
10725 static inline bool
neglectable_inst_p(tree d)10726 neglectable_inst_p (tree d)
10727 {
10728   return (d && DECL_P (d)
10729 	  && !undeduced_auto_decl (d)
10730 	  && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
10731 	       : decl_maybe_constant_var_p (d)));
10732 }
10733 
10734 /* Returns TRUE iff we should refuse to instantiate DECL because it's
10735    neglectable and instantiated from within an erroneous instantiation.  */
10736 
10737 static bool
limit_bad_template_recursion(tree decl)10738 limit_bad_template_recursion (tree decl)
10739 {
10740   struct tinst_level *lev = current_tinst_level;
10741   int errs = errorcount + sorrycount;
10742   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
10743     return false;
10744 
10745   for (; lev; lev = lev->next)
10746     if (neglectable_inst_p (lev->maybe_get_node ()))
10747       break;
10748 
10749   return (lev && errs > lev->errors);
10750 }
10751 
10752 static int tinst_depth;
10753 extern int max_tinst_depth;
10754 int depth_reached;
10755 
10756 static GTY(()) struct tinst_level *last_error_tinst_level;
10757 
10758 /* We're starting to instantiate D; record the template instantiation context
10759    at LOC for diagnostics and to restore it later.  */
10760 
10761 static bool
push_tinst_level_loc(tree tldcl,tree targs,location_t loc)10762 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
10763 {
10764   struct tinst_level *new_level;
10765 
10766   if (tinst_depth >= max_tinst_depth)
10767     {
10768       /* Tell error.c not to try to instantiate any templates.  */
10769       at_eof = 2;
10770       fatal_error (input_location,
10771 		   "template instantiation depth exceeds maximum of %d"
10772 		   " (use %<-ftemplate-depth=%> to increase the maximum)",
10773                    max_tinst_depth);
10774       return false;
10775     }
10776 
10777   /* If the current instantiation caused problems, don't let it instantiate
10778      anything else.  Do allow deduction substitution and decls usable in
10779      constant expressions.  */
10780   if (!targs && limit_bad_template_recursion (tldcl))
10781     {
10782       /* Avoid no_linkage_errors and unused function warnings for this
10783 	 decl.  */
10784       TREE_NO_WARNING (tldcl) = 1;
10785       return false;
10786     }
10787 
10788   /* When not -quiet, dump template instantiations other than functions, since
10789      announce_function will take care of those.  */
10790   if (!quiet_flag && !targs
10791       && TREE_CODE (tldcl) != TREE_LIST
10792       && TREE_CODE (tldcl) != FUNCTION_DECL)
10793     fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
10794 
10795   new_level = tinst_level_freelist ().alloc ();
10796   new_level->tldcl = tldcl;
10797   new_level->targs = targs;
10798   new_level->locus = loc;
10799   new_level->errors = errorcount + sorrycount;
10800   new_level->next = NULL;
10801   new_level->refcount = 0;
10802   set_refcount_ptr (new_level->next, current_tinst_level);
10803   set_refcount_ptr (current_tinst_level, new_level);
10804 
10805   ++tinst_depth;
10806   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
10807     depth_reached = tinst_depth;
10808 
10809   return true;
10810 }
10811 
10812 /* We're starting substitution of TMPL<ARGS>; record the template
10813    substitution context for diagnostics and to restore it later.  */
10814 
10815 static bool
push_tinst_level(tree tmpl,tree args)10816 push_tinst_level (tree tmpl, tree args)
10817 {
10818   return push_tinst_level_loc (tmpl, args, input_location);
10819 }
10820 
10821 /* We're starting to instantiate D; record INPUT_LOCATION and the
10822    template instantiation context for diagnostics and to restore it
10823    later.  */
10824 
10825 bool
push_tinst_level(tree d)10826 push_tinst_level (tree d)
10827 {
10828   return push_tinst_level_loc (d, input_location);
10829 }
10830 
10831 /* Likewise, but record LOC as the program location.  */
10832 
10833 bool
push_tinst_level_loc(tree d,location_t loc)10834 push_tinst_level_loc (tree d, location_t loc)
10835 {
10836   gcc_assert (TREE_CODE (d) != TREE_LIST);
10837   return push_tinst_level_loc (d, NULL, loc);
10838 }
10839 
10840 /* We're done instantiating this template; return to the instantiation
10841    context.  */
10842 
10843 void
pop_tinst_level(void)10844 pop_tinst_level (void)
10845 {
10846   /* Restore the filename and line number stashed away when we started
10847      this instantiation.  */
10848   input_location = current_tinst_level->locus;
10849   set_refcount_ptr (current_tinst_level, current_tinst_level->next);
10850   --tinst_depth;
10851 }
10852 
10853 /* We're instantiating a deferred template; restore the template
10854    instantiation context in which the instantiation was requested, which
10855    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
10856 
10857 static tree
reopen_tinst_level(struct tinst_level * level)10858 reopen_tinst_level (struct tinst_level *level)
10859 {
10860   struct tinst_level *t;
10861 
10862   tinst_depth = 0;
10863   for (t = level; t; t = t->next)
10864     ++tinst_depth;
10865 
10866   set_refcount_ptr (current_tinst_level, level);
10867   pop_tinst_level ();
10868   if (current_tinst_level)
10869     current_tinst_level->errors = errorcount+sorrycount;
10870   return level->maybe_get_node ();
10871 }
10872 
10873 /* Returns the TINST_LEVEL which gives the original instantiation
10874    context.  */
10875 
10876 struct tinst_level *
outermost_tinst_level(void)10877 outermost_tinst_level (void)
10878 {
10879   struct tinst_level *level = current_tinst_level;
10880   if (level)
10881     while (level->next)
10882       level = level->next;
10883   return level;
10884 }
10885 
10886 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
10887    vector of template arguments, as for tsubst.
10888 
10889    Returns an appropriate tsubst'd friend declaration.  */
10890 
10891 static tree
tsubst_friend_function(tree decl,tree args)10892 tsubst_friend_function (tree decl, tree args)
10893 {
10894   tree new_friend;
10895 
10896   if (TREE_CODE (decl) == FUNCTION_DECL
10897       && DECL_TEMPLATE_INSTANTIATION (decl)
10898       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
10899     /* This was a friend declared with an explicit template
10900        argument list, e.g.:
10901 
10902        friend void f<>(T);
10903 
10904        to indicate that f was a template instantiation, not a new
10905        function declaration.  Now, we have to figure out what
10906        instantiation of what template.  */
10907     {
10908       tree template_id, arglist, fns;
10909       tree new_args;
10910       tree tmpl;
10911       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
10912 
10913       /* Friend functions are looked up in the containing namespace scope.
10914 	 We must enter that scope, to avoid finding member functions of the
10915 	 current class with same name.  */
10916       push_nested_namespace (ns);
10917       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
10918 			 tf_warning_or_error, NULL_TREE,
10919 			 /*integral_constant_expression_p=*/false);
10920       pop_nested_namespace (ns);
10921       arglist = tsubst (DECL_TI_ARGS (decl), args,
10922 			tf_warning_or_error, NULL_TREE);
10923       template_id = lookup_template_function (fns, arglist);
10924 
10925       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10926       tmpl = determine_specialization (template_id, new_friend,
10927 				       &new_args,
10928 				       /*need_member_template=*/0,
10929 				       TREE_VEC_LENGTH (args),
10930 				       tsk_none);
10931       return instantiate_template (tmpl, new_args, tf_error);
10932     }
10933 
10934   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10935 
10936   /* The NEW_FRIEND will look like an instantiation, to the
10937      compiler, but is not an instantiation from the point of view of
10938      the language.  For example, we might have had:
10939 
10940      template <class T> struct S {
10941        template <class U> friend void f(T, U);
10942      };
10943 
10944      Then, in S<int>, template <class U> void f(int, U) is not an
10945      instantiation of anything.  */
10946   if (new_friend == error_mark_node)
10947     return error_mark_node;
10948 
10949   DECL_USE_TEMPLATE (new_friend) = 0;
10950   if (TREE_CODE (decl) == TEMPLATE_DECL)
10951     {
10952       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
10953       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
10954 	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
10955 
10956       /* Substitute TEMPLATE_PARMS_CONSTRAINTS so that parameter levels will
10957 	 match in decls_match.  */
10958       tree parms = DECL_TEMPLATE_PARMS (new_friend);
10959       tree treqs = TEMPLATE_PARMS_CONSTRAINTS (parms);
10960       treqs = maybe_substitute_reqs_for (treqs, new_friend);
10961       TEMPLATE_PARMS_CONSTRAINTS (parms) = treqs;
10962     }
10963 
10964   /* The mangled name for the NEW_FRIEND is incorrect.  The function
10965      is not a template instantiation and should not be mangled like
10966      one.  Therefore, we forget the mangling here; we'll recompute it
10967      later if we need it.  */
10968   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
10969     {
10970       SET_DECL_RTL (new_friend, NULL);
10971       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
10972     }
10973 
10974   if (DECL_NAMESPACE_SCOPE_P (new_friend))
10975     {
10976       tree old_decl;
10977       tree new_friend_template_info;
10978       tree new_friend_result_template_info;
10979       tree ns;
10980       int  new_friend_is_defn;
10981 
10982       /* We must save some information from NEW_FRIEND before calling
10983 	 duplicate decls since that function will free NEW_FRIEND if
10984 	 possible.  */
10985       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
10986       new_friend_is_defn =
10987 	    (DECL_INITIAL (DECL_TEMPLATE_RESULT
10988 			   (template_for_substitution (new_friend)))
10989 	     != NULL_TREE);
10990       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
10991 	{
10992 	  /* This declaration is a `primary' template.  */
10993 	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
10994 
10995 	  new_friend_result_template_info
10996 	    = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
10997 	}
10998       else
10999 	new_friend_result_template_info = NULL_TREE;
11000 
11001       /* Inside pushdecl_namespace_level, we will push into the
11002 	 current namespace. However, the friend function should go
11003 	 into the namespace of the template.  */
11004       ns = decl_namespace_context (new_friend);
11005       push_nested_namespace (ns);
11006       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
11007       pop_nested_namespace (ns);
11008 
11009       if (old_decl == error_mark_node)
11010 	return error_mark_node;
11011 
11012       if (old_decl != new_friend)
11013 	{
11014 	  /* This new friend declaration matched an existing
11015 	     declaration.  For example, given:
11016 
11017 	       template <class T> void f(T);
11018 	       template <class U> class C {
11019 		 template <class T> friend void f(T) {}
11020 	       };
11021 
11022 	     the friend declaration actually provides the definition
11023 	     of `f', once C has been instantiated for some type.  So,
11024 	     old_decl will be the out-of-class template declaration,
11025 	     while new_friend is the in-class definition.
11026 
11027 	     But, if `f' was called before this point, the
11028 	     instantiation of `f' will have DECL_TI_ARGS corresponding
11029 	     to `T' but not to `U', references to which might appear
11030 	     in the definition of `f'.  Previously, the most general
11031 	     template for an instantiation of `f' was the out-of-class
11032 	     version; now it is the in-class version.  Therefore, we
11033 	     run through all specialization of `f', adding to their
11034 	     DECL_TI_ARGS appropriately.  In particular, they need a
11035 	     new set of outer arguments, corresponding to the
11036 	     arguments for this class instantiation.
11037 
11038 	     The same situation can arise with something like this:
11039 
11040 	       friend void f(int);
11041 	       template <class T> class C {
11042 		 friend void f(T) {}
11043 	       };
11044 
11045 	     when `C<int>' is instantiated.  Now, `f(int)' is defined
11046 	     in the class.  */
11047 
11048 	  if (!new_friend_is_defn)
11049 	    /* On the other hand, if the in-class declaration does
11050 	       *not* provide a definition, then we don't want to alter
11051 	       existing definitions.  We can just leave everything
11052 	       alone.  */
11053 	    ;
11054 	  else
11055 	    {
11056 	      tree new_template = TI_TEMPLATE (new_friend_template_info);
11057 	      tree new_args = TI_ARGS (new_friend_template_info);
11058 
11059 	      /* Overwrite whatever template info was there before, if
11060 		 any, with the new template information pertaining to
11061 		 the declaration.  */
11062 	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
11063 
11064 	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
11065 		{
11066 		  /* We should have called reregister_specialization in
11067 		     duplicate_decls.  */
11068 		  gcc_assert (retrieve_specialization (new_template,
11069 						       new_args, 0)
11070 			      == old_decl);
11071 
11072 		  /* Instantiate it if the global has already been used.  */
11073 		  if (DECL_ODR_USED (old_decl))
11074 		    instantiate_decl (old_decl, /*defer_ok=*/true,
11075 				      /*expl_inst_class_mem_p=*/false);
11076 		}
11077 	      else
11078 		{
11079 		  tree t;
11080 
11081 		  /* Indicate that the old function template is a partial
11082 		     instantiation.  */
11083 		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
11084 		    = new_friend_result_template_info;
11085 
11086 		  gcc_assert (new_template
11087 			      == most_general_template (new_template));
11088 		  gcc_assert (new_template != old_decl);
11089 
11090 		  /* Reassign any specializations already in the hash table
11091 		     to the new more general template, and add the
11092 		     additional template args.  */
11093 		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
11094 		       t != NULL_TREE;
11095 		       t = TREE_CHAIN (t))
11096 		    {
11097 		      tree spec = TREE_VALUE (t);
11098 		      spec_entry elt;
11099 
11100 		      elt.tmpl = old_decl;
11101 		      elt.args = DECL_TI_ARGS (spec);
11102 		      elt.spec = NULL_TREE;
11103 
11104 		      decl_specializations->remove_elt (&elt);
11105 
11106 		      DECL_TI_ARGS (spec)
11107 			= add_outermost_template_args (new_args,
11108 						       DECL_TI_ARGS (spec));
11109 
11110 		      register_specialization
11111 			(spec, new_template, DECL_TI_ARGS (spec), true, 0);
11112 
11113 		    }
11114 		  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
11115 		}
11116 	    }
11117 
11118 	  /* The information from NEW_FRIEND has been merged into OLD_DECL
11119 	     by duplicate_decls.  */
11120 	  new_friend = old_decl;
11121 	}
11122     }
11123   else
11124     {
11125       tree context = DECL_CONTEXT (new_friend);
11126       bool dependent_p;
11127 
11128       /* In the code
11129 	   template <class T> class C {
11130 	     template <class U> friend void C1<U>::f (); // case 1
11131 	     friend void C2<T>::f ();			 // case 2
11132 	   };
11133 	 we only need to make sure CONTEXT is a complete type for
11134 	 case 2.  To distinguish between the two cases, we note that
11135 	 CONTEXT of case 1 remains dependent type after tsubst while
11136 	 this isn't true for case 2.  */
11137       ++processing_template_decl;
11138       dependent_p = dependent_type_p (context);
11139       --processing_template_decl;
11140 
11141       if (!dependent_p
11142 	  && !complete_type_or_else (context, NULL_TREE))
11143 	return error_mark_node;
11144 
11145       if (COMPLETE_TYPE_P (context))
11146 	{
11147 	  tree fn = new_friend;
11148 	  /* do_friend adds the TEMPLATE_DECL for any member friend
11149 	     template even if it isn't a member template, i.e.
11150 	       template <class T> friend A<T>::f();
11151 	     Look through it in that case.  */
11152 	  if (TREE_CODE (fn) == TEMPLATE_DECL
11153 	      && !PRIMARY_TEMPLATE_P (fn))
11154 	    fn = DECL_TEMPLATE_RESULT (fn);
11155 	  /* Check to see that the declaration is really present, and,
11156 	     possibly obtain an improved declaration.  */
11157 	  fn = check_classfn (context, fn, NULL_TREE);
11158 
11159 	  if (fn)
11160 	    new_friend = fn;
11161 	}
11162     }
11163 
11164   return new_friend;
11165 }
11166 
11167 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
11168    template arguments, as for tsubst.
11169 
11170    Returns an appropriate tsubst'd friend type or error_mark_node on
11171    failure.  */
11172 
11173 static tree
tsubst_friend_class(tree friend_tmpl,tree args)11174 tsubst_friend_class (tree friend_tmpl, tree args)
11175 {
11176   tree tmpl;
11177 
11178   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
11179     {
11180       tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
11181       return TREE_TYPE (tmpl);
11182     }
11183 
11184   tree context = CP_DECL_CONTEXT (friend_tmpl);
11185   if (TREE_CODE (context) == NAMESPACE_DECL)
11186     push_nested_namespace (context);
11187   else
11188     {
11189       context = tsubst (context, args, tf_error, NULL_TREE);
11190       push_nested_class (context);
11191     }
11192 
11193   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), /*prefer_type=*/false,
11194 			   /*non_class=*/false, /*block_p=*/false,
11195 			   /*namespaces_only=*/false, LOOKUP_HIDDEN);
11196 
11197   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
11198     {
11199       /* The friend template has already been declared.  Just
11200 	 check to see that the declarations match, and install any new
11201 	 default parameters.  We must tsubst the default parameters,
11202 	 of course.  We only need the innermost template parameters
11203 	 because that is all that redeclare_class_template will look
11204 	 at.  */
11205       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
11206 	  > TMPL_ARGS_DEPTH (args))
11207 	{
11208 	  tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
11209 					      args, tf_warning_or_error);
11210           location_t saved_input_location = input_location;
11211           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
11212           tree cons = get_constraints (tmpl);
11213           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
11214           input_location = saved_input_location;
11215 	}
11216     }
11217   else
11218     {
11219       /* The friend template has not already been declared.  In this
11220 	 case, the instantiation of the template class will cause the
11221 	 injection of this template into the namespace scope.  */
11222       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
11223 
11224       if (tmpl != error_mark_node)
11225 	{
11226 	  /* The new TMPL is not an instantiation of anything, so we
11227 	     forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE
11228 	     for the new type because that is supposed to be the
11229 	     corresponding template decl, i.e., TMPL.  */
11230 	  DECL_USE_TEMPLATE (tmpl) = 0;
11231 	  DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
11232 	  CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
11233 	  CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
11234 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
11235 
11236 	  /* It is hidden.  */
11237 	  retrofit_lang_decl (DECL_TEMPLATE_RESULT (tmpl));
11238 	  DECL_ANTICIPATED (tmpl)
11239 	    = DECL_ANTICIPATED (DECL_TEMPLATE_RESULT (tmpl)) = true;
11240 
11241 	  /* Substitute into and set the constraints on the new declaration.  */
11242 	  if (tree ci = get_constraints (friend_tmpl))
11243 	    {
11244 	      ++processing_template_decl;
11245 	      ci = tsubst_constraint_info (ci, args, tf_warning_or_error,
11246 					   DECL_FRIEND_CONTEXT (friend_tmpl));
11247 	      --processing_template_decl;
11248 	      set_constraints (tmpl, ci);
11249 	    }
11250 
11251 	  /* Inject this template into the enclosing namspace scope.  */
11252 	  tmpl = pushdecl_namespace_level (tmpl, true);
11253 	}
11254     }
11255 
11256   if (TREE_CODE (context) == NAMESPACE_DECL)
11257     pop_nested_namespace (context);
11258   else
11259     pop_nested_class ();
11260 
11261   return TREE_TYPE (tmpl);
11262 }
11263 
11264 /* Returns zero if TYPE cannot be completed later due to circularity.
11265    Otherwise returns one.  */
11266 
11267 static int
can_complete_type_without_circularity(tree type)11268 can_complete_type_without_circularity (tree type)
11269 {
11270   if (type == NULL_TREE || type == error_mark_node)
11271     return 0;
11272   else if (COMPLETE_TYPE_P (type))
11273     return 1;
11274   else if (TREE_CODE (type) == ARRAY_TYPE)
11275     return can_complete_type_without_circularity (TREE_TYPE (type));
11276   else if (CLASS_TYPE_P (type)
11277 	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
11278     return 0;
11279   else
11280     return 1;
11281 }
11282 
11283 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
11284 				tsubst_flags_t, tree);
11285 
11286 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
11287    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
11288 
11289 static tree
tsubst_attribute(tree t,tree * decl_p,tree args,tsubst_flags_t complain,tree in_decl)11290 tsubst_attribute (tree t, tree *decl_p, tree args,
11291 		  tsubst_flags_t complain, tree in_decl)
11292 {
11293   gcc_assert (ATTR_IS_DEPENDENT (t));
11294 
11295   tree val = TREE_VALUE (t);
11296   if (val == NULL_TREE)
11297     /* Nothing to do.  */;
11298   else if ((flag_openmp || flag_openmp_simd)
11299 	   && is_attribute_p ("omp declare simd",
11300 			      get_attribute_name (t)))
11301     {
11302       tree clauses = TREE_VALUE (val);
11303       clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
11304 				    complain, in_decl);
11305       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11306       clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11307       tree parms = DECL_ARGUMENTS (*decl_p);
11308       clauses
11309 	= c_omp_declare_simd_clauses_to_numbers (parms, clauses);
11310       if (clauses)
11311 	val = build_tree_list (NULL_TREE, clauses);
11312       else
11313 	val = NULL_TREE;
11314     }
11315   else if (flag_openmp
11316 	   && is_attribute_p ("omp declare variant base",
11317 			      get_attribute_name (t)))
11318     {
11319       ++cp_unevaluated_operand;
11320       tree varid
11321 	= tsubst_expr (TREE_PURPOSE (val), args, complain,
11322 		       in_decl, /*integral_constant_expression_p=*/false);
11323       --cp_unevaluated_operand;
11324       tree chain = TREE_CHAIN (val);
11325       location_t match_loc = cp_expr_loc_or_input_loc (TREE_PURPOSE (chain));
11326       tree ctx = copy_list (TREE_VALUE (val));
11327       tree simd = get_identifier ("simd");
11328       tree score = get_identifier (" score");
11329       tree condition = get_identifier ("condition");
11330       for (tree t1 = ctx; t1; t1 = TREE_CHAIN (t1))
11331 	{
11332 	  const char *set = IDENTIFIER_POINTER (TREE_PURPOSE (t1));
11333 	  TREE_VALUE (t1) = copy_list (TREE_VALUE (t1));
11334 	  for (tree t2 = TREE_VALUE (t1); t2; t2 = TREE_CHAIN (t2))
11335 	    {
11336 	      if (TREE_PURPOSE (t2) == simd && set[0] == 'c')
11337 		{
11338 		  tree clauses = TREE_VALUE (t2);
11339 		  clauses = tsubst_omp_clauses (clauses,
11340 						C_ORT_OMP_DECLARE_SIMD, args,
11341 						complain, in_decl);
11342 		  c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
11343 		  clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
11344 		  TREE_VALUE (t2) = clauses;
11345 		}
11346 	      else
11347 		{
11348 		  TREE_VALUE (t2) = copy_list (TREE_VALUE (t2));
11349 		  for (tree t3 = TREE_VALUE (t2); t3; t3 = TREE_CHAIN (t3))
11350 		    if (TREE_VALUE (t3))
11351 		      {
11352 			bool allow_string
11353 			  = ((TREE_PURPOSE (t2) != condition || set[0] != 'u')
11354 			     && TREE_PURPOSE (t3) != score);
11355 			tree v = TREE_VALUE (t3);
11356 			if (TREE_CODE (v) == STRING_CST && allow_string)
11357 			  continue;
11358 			v = tsubst_expr (v, args, complain, in_decl, true);
11359 			v = fold_non_dependent_expr (v);
11360 			if (!INTEGRAL_TYPE_P (TREE_TYPE (v))
11361 			    || (TREE_PURPOSE (t3) == score
11362 				? TREE_CODE (v) != INTEGER_CST
11363 				: !tree_fits_shwi_p (v)))
11364 			  {
11365 			    location_t loc
11366 			      = cp_expr_loc_or_loc (TREE_VALUE (t3),
11367 						    match_loc);
11368 			    if (TREE_PURPOSE (t3) == score)
11369 			      error_at (loc, "score argument must be "
11370 					     "constant integer expression");
11371 			    else if (allow_string)
11372 			      error_at (loc, "property must be constant "
11373 					     "integer expression or string "
11374 					     "literal");
11375 			    else
11376 			      error_at (loc, "property must be constant "
11377 					     "integer expression");
11378 			    return NULL_TREE;
11379 			  }
11380 			else if (TREE_PURPOSE (t3) == score
11381 				 && tree_int_cst_sgn (v) < 0)
11382 			  {
11383 			    location_t loc
11384 			      = cp_expr_loc_or_loc (TREE_VALUE (t3),
11385 						    match_loc);
11386 			    error_at (loc, "score argument must be "
11387 					   "non-negative");
11388 			    return NULL_TREE;
11389 			  }
11390 			TREE_VALUE (t3) = v;
11391 		      }
11392 		}
11393 	    }
11394 	}
11395       val = tree_cons (varid, ctx, chain);
11396     }
11397   /* If the first attribute argument is an identifier, don't
11398      pass it through tsubst.  Attributes like mode, format,
11399      cleanup and several target specific attributes expect it
11400      unmodified.  */
11401   else if (attribute_takes_identifier_p (get_attribute_name (t)))
11402     {
11403       tree chain
11404 	= tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
11405 		       /*integral_constant_expression_p=*/false);
11406       if (chain != TREE_CHAIN (val))
11407 	val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
11408     }
11409   else if (PACK_EXPANSION_P (val))
11410     {
11411       /* An attribute pack expansion.  */
11412       tree purp = TREE_PURPOSE (t);
11413       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
11414       if (pack == error_mark_node)
11415 	return error_mark_node;
11416       int len = TREE_VEC_LENGTH (pack);
11417       tree list = NULL_TREE;
11418       tree *q = &list;
11419       for (int i = 0; i < len; ++i)
11420 	{
11421 	  tree elt = TREE_VEC_ELT (pack, i);
11422 	  *q = build_tree_list (purp, elt);
11423 	  q = &TREE_CHAIN (*q);
11424 	}
11425       return list;
11426     }
11427   else
11428     val = tsubst_expr (val, args, complain, in_decl,
11429 		       /*integral_constant_expression_p=*/false);
11430 
11431   if (val != TREE_VALUE (t))
11432     return build_tree_list (TREE_PURPOSE (t), val);
11433   return t;
11434 }
11435 
11436 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
11437    unchanged or a new TREE_LIST chain.  */
11438 
11439 static tree
tsubst_attributes(tree attributes,tree args,tsubst_flags_t complain,tree in_decl)11440 tsubst_attributes (tree attributes, tree args,
11441 		   tsubst_flags_t complain, tree in_decl)
11442 {
11443   tree last_dep = NULL_TREE;
11444 
11445   for (tree t = attributes; t; t = TREE_CHAIN (t))
11446     if (ATTR_IS_DEPENDENT (t))
11447       {
11448 	last_dep = t;
11449 	attributes = copy_list (attributes);
11450 	break;
11451       }
11452 
11453   if (last_dep)
11454     for (tree *p = &attributes; *p; )
11455       {
11456 	tree t = *p;
11457 	if (ATTR_IS_DEPENDENT (t))
11458 	  {
11459 	    tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
11460 	    if (subst != t)
11461 	      {
11462 		*p = subst;
11463 		while (*p)
11464 		  p = &TREE_CHAIN (*p);
11465 		*p = TREE_CHAIN (t);
11466 		continue;
11467 	      }
11468 	  }
11469 	p = &TREE_CHAIN (*p);
11470       }
11471 
11472   return attributes;
11473 }
11474 
11475 /* Apply any attributes which had to be deferred until instantiation
11476    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
11477    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
11478 
11479 static void
apply_late_template_attributes(tree * decl_p,tree attributes,int attr_flags,tree args,tsubst_flags_t complain,tree in_decl)11480 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
11481 				tree args, tsubst_flags_t complain, tree in_decl)
11482 {
11483   tree last_dep = NULL_TREE;
11484   tree t;
11485   tree *p;
11486 
11487   if (attributes == NULL_TREE)
11488     return;
11489 
11490   if (DECL_P (*decl_p))
11491     {
11492       if (TREE_TYPE (*decl_p) == error_mark_node)
11493 	return;
11494       p = &DECL_ATTRIBUTES (*decl_p);
11495       /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
11496          to our attributes parameter.  */
11497       gcc_assert (*p == attributes);
11498     }
11499   else
11500     {
11501       p = &TYPE_ATTRIBUTES (*decl_p);
11502       /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
11503 	 lookup_template_class_1, and should be preserved.  */
11504       gcc_assert (*p != attributes);
11505       while (*p)
11506 	p = &TREE_CHAIN (*p);
11507     }
11508 
11509   for (t = attributes; t; t = TREE_CHAIN (t))
11510     if (ATTR_IS_DEPENDENT (t))
11511       {
11512 	last_dep = t;
11513 	attributes = copy_list (attributes);
11514 	break;
11515       }
11516 
11517   *p = attributes;
11518   if (last_dep)
11519     {
11520       tree late_attrs = NULL_TREE;
11521       tree *q = &late_attrs;
11522 
11523       for (; *p; )
11524 	{
11525 	  t = *p;
11526 	  if (ATTR_IS_DEPENDENT (t))
11527 	    {
11528 	      *p = TREE_CHAIN (t);
11529 	      TREE_CHAIN (t) = NULL_TREE;
11530 	      *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
11531 	      while (*q)
11532 		q = &TREE_CHAIN (*q);
11533 	    }
11534 	  else
11535 	    p = &TREE_CHAIN (t);
11536 	}
11537 
11538       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
11539     }
11540 }
11541 
11542 /* Perform (or defer) access check for typedefs that were referenced
11543    from within the template TMPL code.
11544    This is a subroutine of instantiate_decl and instantiate_class_template.
11545    TMPL is the template to consider and TARGS is the list of arguments of
11546    that template.  */
11547 
11548 static void
perform_typedefs_access_check(tree tmpl,tree targs)11549 perform_typedefs_access_check (tree tmpl, tree targs)
11550 {
11551   unsigned i;
11552   qualified_typedef_usage_t *iter;
11553 
11554   if (!tmpl
11555       || (!CLASS_TYPE_P (tmpl)
11556 	  && TREE_CODE (tmpl) != FUNCTION_DECL))
11557     return;
11558 
11559   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
11560     {
11561       tree type_decl = iter->typedef_decl;
11562       tree type_scope = iter->context;
11563 
11564       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
11565 	continue;
11566 
11567       if (uses_template_parms (type_decl))
11568 	type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
11569       if (uses_template_parms (type_scope))
11570 	type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
11571 
11572       /* Make access check error messages point to the location
11573          of the use of the typedef.  */
11574       iloc_sentinel ils (iter->locus);
11575       perform_or_defer_access_check (TYPE_BINFO (type_scope),
11576 				     type_decl, type_decl,
11577 				     tf_warning_or_error);
11578     }
11579 }
11580 
11581 static tree
instantiate_class_template_1(tree type)11582 instantiate_class_template_1 (tree type)
11583 {
11584   tree templ, args, pattern, t, member;
11585   tree typedecl;
11586   tree pbinfo;
11587   tree base_list;
11588   unsigned int saved_maximum_field_alignment;
11589   tree fn_context;
11590 
11591   if (type == error_mark_node)
11592     return error_mark_node;
11593 
11594   if (COMPLETE_OR_OPEN_TYPE_P (type)
11595       || uses_template_parms (type))
11596     return type;
11597 
11598   /* Figure out which template is being instantiated.  */
11599   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
11600   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
11601 
11602   /* Mark the type as in the process of being defined.  */
11603   TYPE_BEING_DEFINED (type) = 1;
11604 
11605   /* We may be in the middle of deferred access check.  Disable
11606      it now.  */
11607   deferring_access_check_sentinel acs (dk_no_deferred);
11608 
11609   /* Determine what specialization of the original template to
11610      instantiate.  */
11611   t = most_specialized_partial_spec (type, tf_warning_or_error);
11612   if (t == error_mark_node)
11613     return error_mark_node;
11614   else if (t)
11615     {
11616       /* This TYPE is actually an instantiation of a partial
11617 	 specialization.  We replace the innermost set of ARGS with
11618 	 the arguments appropriate for substitution.  For example,
11619 	 given:
11620 
11621 	   template <class T> struct S {};
11622 	   template <class T> struct S<T*> {};
11623 
11624 	 and supposing that we are instantiating S<int*>, ARGS will
11625 	 presently be {int*} -- but we need {int}.  */
11626       pattern = TREE_TYPE (t);
11627       args = TREE_PURPOSE (t);
11628     }
11629   else
11630     {
11631       pattern = TREE_TYPE (templ);
11632       args = CLASSTYPE_TI_ARGS (type);
11633     }
11634 
11635   /* If the template we're instantiating is incomplete, then clearly
11636      there's nothing we can do.  */
11637   if (!COMPLETE_TYPE_P (pattern))
11638     {
11639       /* We can try again later.  */
11640       TYPE_BEING_DEFINED (type) = 0;
11641       return type;
11642     }
11643 
11644   /* If we've recursively instantiated too many templates, stop.  */
11645   if (! push_tinst_level (type))
11646     return type;
11647 
11648   int saved_unevaluated_operand = cp_unevaluated_operand;
11649   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
11650 
11651   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
11652   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
11653   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
11654     fn_context = error_mark_node;
11655   if (!fn_context)
11656     push_to_top_level ();
11657   else
11658     {
11659       cp_unevaluated_operand = 0;
11660       c_inhibit_evaluation_warnings = 0;
11661     }
11662   /* Use #pragma pack from the template context.  */
11663   saved_maximum_field_alignment = maximum_field_alignment;
11664   maximum_field_alignment = TYPE_PRECISION (pattern);
11665 
11666   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
11667 
11668   /* Set the input location to the most specialized template definition.
11669      This is needed if tsubsting causes an error.  */
11670   typedecl = TYPE_MAIN_DECL (pattern);
11671   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
11672     DECL_SOURCE_LOCATION (typedecl);
11673 
11674   TYPE_PACKED (type) = TYPE_PACKED (pattern);
11675   SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
11676   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
11677   CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
11678   if (ANON_AGGR_TYPE_P (pattern))
11679     SET_ANON_AGGR_TYPE_P (type);
11680   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
11681     {
11682       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
11683       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
11684       /* Adjust visibility for template arguments.  */
11685       determine_visibility (TYPE_MAIN_DECL (type));
11686     }
11687   if (CLASS_TYPE_P (type))
11688     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
11689 
11690   pbinfo = TYPE_BINFO (pattern);
11691 
11692   /* We should never instantiate a nested class before its enclosing
11693      class; we need to look up the nested class by name before we can
11694      instantiate it, and that lookup should instantiate the enclosing
11695      class.  */
11696   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
11697 	      || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
11698 
11699   base_list = NULL_TREE;
11700   if (BINFO_N_BASE_BINFOS (pbinfo))
11701     {
11702       tree pbase_binfo;
11703       tree pushed_scope;
11704       int i;
11705 
11706       /* We must enter the scope containing the type, as that is where
11707 	 the accessibility of types named in dependent bases are
11708 	 looked up from.  */
11709       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
11710 
11711       /* Substitute into each of the bases to determine the actual
11712 	 basetypes.  */
11713       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
11714 	{
11715 	  tree base;
11716 	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
11717           tree expanded_bases = NULL_TREE;
11718           int idx, len = 1;
11719 
11720           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
11721             {
11722               expanded_bases =
11723 		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
11724 				       args, tf_error, NULL_TREE);
11725               if (expanded_bases == error_mark_node)
11726                 continue;
11727 
11728               len = TREE_VEC_LENGTH (expanded_bases);
11729             }
11730 
11731           for (idx = 0; idx < len; idx++)
11732             {
11733               if (expanded_bases)
11734                 /* Extract the already-expanded base class.  */
11735                 base = TREE_VEC_ELT (expanded_bases, idx);
11736               else
11737                 /* Substitute to figure out the base class.  */
11738                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
11739                                NULL_TREE);
11740 
11741               if (base == error_mark_node)
11742                 continue;
11743 
11744               base_list = tree_cons (access, base, base_list);
11745               if (BINFO_VIRTUAL_P (pbase_binfo))
11746                 TREE_TYPE (base_list) = integer_type_node;
11747             }
11748 	}
11749 
11750       /* The list is now in reverse order; correct that.  */
11751       base_list = nreverse (base_list);
11752 
11753       if (pushed_scope)
11754 	pop_scope (pushed_scope);
11755     }
11756   /* Now call xref_basetypes to set up all the base-class
11757      information.  */
11758   xref_basetypes (type, base_list);
11759 
11760   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
11761 				  (int) ATTR_FLAG_TYPE_IN_PLACE,
11762 				  args, tf_error, NULL_TREE);
11763   fixup_attribute_variants (type);
11764 
11765   /* Now that our base classes are set up, enter the scope of the
11766      class, so that name lookups into base classes, etc. will work
11767      correctly.  This is precisely analogous to what we do in
11768      begin_class_definition when defining an ordinary non-template
11769      class, except we also need to push the enclosing classes.  */
11770   push_nested_class (type);
11771 
11772   /* A vector to hold members marked with attribute used. */
11773   auto_vec<tree> used;
11774 
11775   /* Now members are processed in the order of declaration.  */
11776   for (member = CLASSTYPE_DECL_LIST (pattern);
11777        member; member = TREE_CHAIN (member))
11778     {
11779       tree t = TREE_VALUE (member);
11780 
11781       if (TREE_PURPOSE (member))
11782 	{
11783 	  if (TYPE_P (t))
11784 	    {
11785 	      if (LAMBDA_TYPE_P (t))
11786 		/* A closure type for a lambda in an NSDMI or default argument.
11787 		   Ignore it; it will be regenerated when needed.  */
11788 		continue;
11789 
11790 	      /* Build new CLASSTYPE_NESTED_UTDS.  */
11791 
11792 	      tree newtag;
11793 	      bool class_template_p;
11794 
11795 	      class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
11796 				  && TYPE_LANG_SPECIFIC (t)
11797 				  && CLASSTYPE_IS_TEMPLATE (t));
11798 	      /* If the member is a class template, then -- even after
11799 		 substitution -- there may be dependent types in the
11800 		 template argument list for the class.  We increment
11801 		 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
11802 		 that function will assume that no types are dependent
11803 		 when outside of a template.  */
11804 	      if (class_template_p)
11805 		++processing_template_decl;
11806 	      newtag = tsubst (t, args, tf_error, NULL_TREE);
11807 	      if (class_template_p)
11808 		--processing_template_decl;
11809 	      if (newtag == error_mark_node)
11810 		continue;
11811 
11812 	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
11813 		{
11814 		  tree name = TYPE_IDENTIFIER (t);
11815 
11816 		  if (class_template_p)
11817 		    /* Unfortunately, lookup_template_class sets
11818 		       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
11819 		       instantiation (i.e., for the type of a member
11820 		       template class nested within a template class.)
11821 		       This behavior is required for
11822 		       maybe_process_partial_specialization to work
11823 		       correctly, but is not accurate in this case;
11824 		       the TAG is not an instantiation of anything.
11825 		       (The corresponding TEMPLATE_DECL is an
11826 		       instantiation, but the TYPE is not.) */
11827 		    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
11828 
11829 		  /* Now, we call pushtag to put this NEWTAG into the scope of
11830 		     TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
11831 		     pushtag calling push_template_decl.  We don't have to do
11832 		     this for enums because it will already have been done in
11833 		     tsubst_enum.  */
11834 		  if (name)
11835 		    SET_IDENTIFIER_TYPE_VALUE (name, newtag);
11836 		  pushtag (name, newtag, /*tag_scope=*/ts_current);
11837 		}
11838 	    }
11839 	  else if (DECL_DECLARES_FUNCTION_P (t))
11840 	    {
11841 	      tree r;
11842 
11843 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11844 		++processing_template_decl;
11845 	      r = tsubst (t, args, tf_error, NULL_TREE);
11846 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11847 		--processing_template_decl;
11848 	      set_current_access_from_decl (r);
11849 	      finish_member_declaration (r);
11850 	      /* Instantiate members marked with attribute used.  */
11851 	      if (r != error_mark_node && DECL_PRESERVE_P (r))
11852 		used.safe_push (r);
11853 	      if (TREE_CODE (r) == FUNCTION_DECL
11854 		  && DECL_OMP_DECLARE_REDUCTION_P (r))
11855 		cp_check_omp_declare_reduction (r);
11856 	    }
11857 	  else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
11858 		   && LAMBDA_TYPE_P (TREE_TYPE (t)))
11859 	    /* A closure type for a lambda in an NSDMI or default argument.
11860 	       Ignore it; it will be regenerated when needed.  */;
11861 	  else
11862 	    {
11863 	      /* Build new TYPE_FIELDS.  */
11864               if (TREE_CODE (t) == STATIC_ASSERT)
11865                 {
11866                   tree condition;
11867 
11868 		  ++c_inhibit_evaluation_warnings;
11869 		  condition =
11870 		    tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
11871 				 tf_warning_or_error, NULL_TREE,
11872 				 /*integral_constant_expression_p=*/true);
11873 		  --c_inhibit_evaluation_warnings;
11874 
11875                   finish_static_assert (condition,
11876                                         STATIC_ASSERT_MESSAGE (t),
11877                                         STATIC_ASSERT_SOURCE_LOCATION (t),
11878                                         /*member_p=*/true);
11879                 }
11880 	      else if (TREE_CODE (t) != CONST_DECL)
11881 		{
11882 		  tree r;
11883 		  tree vec = NULL_TREE;
11884 		  int len = 1;
11885 
11886 		  /* The file and line for this declaration, to
11887 		     assist in error message reporting.  Since we
11888 		     called push_tinst_level above, we don't need to
11889 		     restore these.  */
11890 		  input_location = DECL_SOURCE_LOCATION (t);
11891 
11892 		  if (TREE_CODE (t) == TEMPLATE_DECL)
11893 		    ++processing_template_decl;
11894 		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
11895 		  if (TREE_CODE (t) == TEMPLATE_DECL)
11896 		    --processing_template_decl;
11897 
11898 		  if (TREE_CODE (r) == TREE_VEC)
11899 		    {
11900 		      /* A capture pack became multiple fields.  */
11901 		      vec = r;
11902 		      len = TREE_VEC_LENGTH (vec);
11903 		    }
11904 
11905 		  for (int i = 0; i < len; ++i)
11906 		    {
11907 		      if (vec)
11908 			r = TREE_VEC_ELT (vec, i);
11909 		      if (VAR_P (r))
11910 			{
11911 			  /* In [temp.inst]:
11912 
11913 			     [t]he initialization (and any associated
11914 			     side-effects) of a static data member does
11915 			     not occur unless the static data member is
11916 			     itself used in a way that requires the
11917 			     definition of the static data member to
11918 			     exist.
11919 
11920 			     Therefore, we do not substitute into the
11921 			     initialized for the static data member here.  */
11922 			  finish_static_data_member_decl
11923 			    (r,
11924 			     /*init=*/NULL_TREE,
11925 			     /*init_const_expr_p=*/false,
11926 			     /*asmspec_tree=*/NULL_TREE,
11927 			     /*flags=*/0);
11928 			  /* Instantiate members marked with attribute used. */
11929 			  if (r != error_mark_node && DECL_PRESERVE_P (r))
11930 			    used.safe_push (r);
11931 			}
11932 		      else if (TREE_CODE (r) == FIELD_DECL)
11933 			{
11934 			  /* Determine whether R has a valid type and can be
11935 			     completed later.  If R is invalid, then its type
11936 			     is replaced by error_mark_node.  */
11937 			  tree rtype = TREE_TYPE (r);
11938 			  if (can_complete_type_without_circularity (rtype))
11939 			    complete_type (rtype);
11940 
11941 			  if (!complete_or_array_type_p (rtype))
11942 			    {
11943 			      /* If R's type couldn't be completed and
11944 				 it isn't a flexible array member (whose
11945 				 type is incomplete by definition) give
11946 				 an error.  */
11947 			      cxx_incomplete_type_error (r, rtype);
11948 			      TREE_TYPE (r) = error_mark_node;
11949 			    }
11950 			  else if (TREE_CODE (rtype) == ARRAY_TYPE
11951 				   && TYPE_DOMAIN (rtype) == NULL_TREE
11952 				   && (TREE_CODE (type) == UNION_TYPE
11953 				       || TREE_CODE (type) == QUAL_UNION_TYPE))
11954 			    {
11955 			      error ("flexible array member %qD in union", r);
11956 			      TREE_TYPE (r) = error_mark_node;
11957 			    }
11958 			  else if (!verify_type_context (input_location,
11959 							 TCTX_FIELD, rtype))
11960 			    TREE_TYPE (r) = error_mark_node;
11961 			}
11962 
11963 		      /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
11964 			 such a thing will already have been added to the field
11965 			 list by tsubst_enum in finish_member_declaration in the
11966 			 CLASSTYPE_NESTED_UTDS case above.  */
11967 		      if (!(TREE_CODE (r) == TYPE_DECL
11968 			    && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
11969 			    && DECL_ARTIFICIAL (r)))
11970 			{
11971 			  set_current_access_from_decl (r);
11972 			  finish_member_declaration (r);
11973 			}
11974 		    }
11975 		}
11976 	    }
11977 	}
11978       else
11979 	{
11980 	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
11981 	      || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11982 	    {
11983 	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
11984 
11985 	      tree friend_type = t;
11986 	      bool adjust_processing_template_decl = false;
11987 
11988 	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11989 		{
11990 		  /* template <class T> friend class C;  */
11991 		  friend_type = tsubst_friend_class (friend_type, args);
11992 		  adjust_processing_template_decl = true;
11993 		}
11994 	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
11995 		{
11996 		  /* template <class T> friend class C::D;  */
11997 		  friend_type = tsubst (friend_type, args,
11998 					tf_warning_or_error, NULL_TREE);
11999 		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
12000 		    friend_type = TREE_TYPE (friend_type);
12001 		  adjust_processing_template_decl = true;
12002 		}
12003 	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE
12004 		       || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
12005 		{
12006 		  /* This could be either
12007 
12008 		       friend class T::C;
12009 
12010 		     when dependent_type_p is false or
12011 
12012 		       template <class U> friend class T::C;
12013 
12014 		     otherwise.  */
12015 		  /* Bump processing_template_decl in case this is something like
12016 		     template <class T> friend struct A<T>::B.  */
12017 		  ++processing_template_decl;
12018 		  friend_type = tsubst (friend_type, args,
12019 					tf_warning_or_error, NULL_TREE);
12020 		  if (dependent_type_p (friend_type))
12021 		    adjust_processing_template_decl = true;
12022 		  --processing_template_decl;
12023 		}
12024 	      else if (TREE_CODE (friend_type) != BOUND_TEMPLATE_TEMPLATE_PARM
12025 		       && !CLASSTYPE_USE_TEMPLATE (friend_type)
12026 		       && TYPE_HIDDEN_P (friend_type))
12027 		{
12028 		  /* friend class C;
12029 
12030 		     where C hasn't been declared yet.  Let's lookup name
12031 		     from namespace scope directly, bypassing any name that
12032 		     come from dependent base class.  */
12033 		  tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
12034 
12035 		  /* The call to xref_tag_from_type does injection for friend
12036 		     classes.  */
12037 		  push_nested_namespace (ns);
12038 		  friend_type =
12039 		    xref_tag_from_type (friend_type, NULL_TREE,
12040 					/*tag_scope=*/ts_current);
12041 		  pop_nested_namespace (ns);
12042 		}
12043 	      else if (uses_template_parms (friend_type))
12044 		/* friend class C<T>;  */
12045 		friend_type = tsubst (friend_type, args,
12046 				      tf_warning_or_error, NULL_TREE);
12047 	      /* Otherwise it's
12048 
12049 		   friend class C;
12050 
12051 		 where C is already declared or
12052 
12053 		   friend class C<int>;
12054 
12055 		 We don't have to do anything in these cases.  */
12056 
12057 	      if (adjust_processing_template_decl)
12058 		/* Trick make_friend_class into realizing that the friend
12059 		   we're adding is a template, not an ordinary class.  It's
12060 		   important that we use make_friend_class since it will
12061 		   perform some error-checking and output cross-reference
12062 		   information.  */
12063 		++processing_template_decl;
12064 
12065 	      if (friend_type != error_mark_node)
12066 		make_friend_class (type, friend_type, /*complain=*/false);
12067 
12068 	      if (adjust_processing_template_decl)
12069 		--processing_template_decl;
12070 	    }
12071 	  else
12072 	    {
12073 	      /* Build new DECL_FRIENDLIST.  */
12074 	      tree r;
12075 
12076 	      /* The file and line for this declaration, to
12077 		 assist in error message reporting.  Since we
12078 		 called push_tinst_level above, we don't need to
12079 		 restore these.  */
12080 	      input_location = DECL_SOURCE_LOCATION (t);
12081 
12082 	      if (TREE_CODE (t) == TEMPLATE_DECL)
12083 		{
12084 		  ++processing_template_decl;
12085 		  push_deferring_access_checks (dk_no_check);
12086 		}
12087 
12088 	      r = tsubst_friend_function (t, args);
12089 	      add_friend (type, r, /*complain=*/false);
12090 	      if (TREE_CODE (t) == TEMPLATE_DECL)
12091 		{
12092 		  pop_deferring_access_checks ();
12093 		  --processing_template_decl;
12094 		}
12095 	    }
12096 	}
12097     }
12098 
12099   if (fn_context)
12100     {
12101       /* Restore these before substituting into the lambda capture
12102 	 initializers.  */
12103       cp_unevaluated_operand = saved_unevaluated_operand;
12104       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12105     }
12106 
12107   /* Set the file and line number information to whatever is given for
12108      the class itself.  This puts error messages involving generated
12109      implicit functions at a predictable point, and the same point
12110      that would be used for non-template classes.  */
12111   input_location = DECL_SOURCE_LOCATION (typedecl);
12112 
12113   unreverse_member_declarations (type);
12114   finish_struct_1 (type);
12115   TYPE_BEING_DEFINED (type) = 0;
12116 
12117   /* We don't instantiate default arguments for member functions.  14.7.1:
12118 
12119      The implicit instantiation of a class template specialization causes
12120      the implicit instantiation of the declarations, but not of the
12121      definitions or default arguments, of the class member functions,
12122      member classes, static data members and member templates....  */
12123 
12124   /* Some typedefs referenced from within the template code need to be access
12125      checked at template instantiation time, i.e now. These types were
12126      added to the template at parsing time. Let's get those and perform
12127      the access checks then.  */
12128   perform_typedefs_access_check (pattern, args);
12129   perform_deferred_access_checks (tf_warning_or_error);
12130   pop_nested_class ();
12131   maximum_field_alignment = saved_maximum_field_alignment;
12132   if (!fn_context)
12133     pop_from_top_level ();
12134   pop_tinst_level ();
12135 
12136   /* The vtable for a template class can be emitted in any translation
12137      unit in which the class is instantiated.  When there is no key
12138      method, however, finish_struct_1 will already have added TYPE to
12139      the keyed_classes.  */
12140   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
12141     vec_safe_push (keyed_classes, type);
12142 
12143   /* Now that we've gone through all the members, instantiate those
12144      marked with attribute used.  */
12145   unsigned int i;
12146   tree x;
12147   FOR_EACH_VEC_ELT (used, i, x)
12148     mark_used (x);
12149 
12150   return type;
12151 }
12152 
12153 /* Wrapper for instantiate_class_template_1.  */
12154 
12155 tree
instantiate_class_template(tree type)12156 instantiate_class_template (tree type)
12157 {
12158   tree ret;
12159   timevar_push (TV_TEMPLATE_INST);
12160   ret = instantiate_class_template_1 (type);
12161   timevar_pop (TV_TEMPLATE_INST);
12162   return ret;
12163 }
12164 
12165 tree
tsubst_template_arg(tree t,tree args,tsubst_flags_t complain,tree in_decl)12166 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12167 {
12168   tree r;
12169 
12170   if (!t)
12171     r = t;
12172   else if (TYPE_P (t))
12173     r = tsubst (t, args, complain, in_decl);
12174   else
12175     {
12176       if (!(complain & tf_warning))
12177 	++c_inhibit_evaluation_warnings;
12178       r = tsubst_expr (t, args, complain, in_decl,
12179 		       /*integral_constant_expression_p=*/true);
12180       if (!(complain & tf_warning))
12181 	--c_inhibit_evaluation_warnings;
12182     }
12183 
12184   return r;
12185 }
12186 
12187 /* Given a function parameter pack TMPL_PARM and some function parameters
12188    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
12189    and set *SPEC_P to point at the next point in the list.  */
12190 
12191 tree
extract_fnparm_pack(tree tmpl_parm,tree * spec_p)12192 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
12193 {
12194   /* Collect all of the extra "packed" parameters into an
12195      argument pack.  */
12196   tree argpack;
12197   tree spec_parm = *spec_p;
12198   int len;
12199 
12200   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
12201     if (tmpl_parm
12202 	&& !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
12203       break;
12204 
12205   spec_parm = *spec_p;
12206   if (len == 1 && DECL_PACK_P (spec_parm))
12207     {
12208       /* The instantiation is still a parameter pack; don't wrap it in a
12209 	 NONTYPE_ARGUMENT_PACK.  */
12210       argpack = spec_parm;
12211       spec_parm = DECL_CHAIN (spec_parm);
12212     }
12213   else
12214     {
12215       /* Fill in PARMVEC with all of the parameters.  */
12216       tree parmvec = make_tree_vec (len);
12217       argpack = make_node (NONTYPE_ARGUMENT_PACK);
12218       for (int i = 0; i < len; i++)
12219 	{
12220 	  tree elt = spec_parm;
12221 	  if (DECL_PACK_P (elt))
12222 	    elt = make_pack_expansion (elt);
12223 	  TREE_VEC_ELT (parmvec, i) = elt;
12224 	  spec_parm = DECL_CHAIN (spec_parm);
12225 	}
12226 
12227       /* Build the argument packs.  */
12228       SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
12229     }
12230   *spec_p = spec_parm;
12231 
12232   return argpack;
12233 }
12234 
12235 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
12236    NONTYPE_ARGUMENT_PACK.  */
12237 
12238 static tree
make_fnparm_pack(tree spec_parm)12239 make_fnparm_pack (tree spec_parm)
12240 {
12241   return extract_fnparm_pack (NULL_TREE, &spec_parm);
12242 }
12243 
12244 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
12245    pack expansion with no extra args, 2 if it has extra args, or 0
12246    if it is not a pack expansion.  */
12247 
12248 static int
argument_pack_element_is_expansion_p(tree arg_pack,int i)12249 argument_pack_element_is_expansion_p (tree arg_pack, int i)
12250 {
12251   if (TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12252     /* We're being called before this happens in tsubst_pack_expansion.  */
12253     arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12254   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
12255   if (i >= TREE_VEC_LENGTH (vec))
12256     return 0;
12257   tree elt = TREE_VEC_ELT (vec, i);
12258   if (DECL_P (elt))
12259     /* A decl pack is itself an expansion.  */
12260     elt = TREE_TYPE (elt);
12261   if (!PACK_EXPANSION_P (elt))
12262     return 0;
12263   if (PACK_EXPANSION_EXTRA_ARGS (elt))
12264     return 2;
12265   return 1;
12266 }
12267 
12268 
12269 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
12270 
12271 static tree
make_argument_pack_select(tree arg_pack,unsigned index)12272 make_argument_pack_select (tree arg_pack, unsigned index)
12273 {
12274   tree aps = make_node (ARGUMENT_PACK_SELECT);
12275 
12276   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
12277   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12278 
12279   return aps;
12280 }
12281 
12282 /*  This is a subroutine of tsubst_pack_expansion.
12283 
12284     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
12285     mechanism to store the (non complete list of) arguments of the
12286     substitution and return a non substituted pack expansion, in order
12287     to wait for when we have enough arguments to really perform the
12288     substitution.  */
12289 
12290 static bool
use_pack_expansion_extra_args_p(tree parm_packs,int arg_pack_len,bool has_empty_arg)12291 use_pack_expansion_extra_args_p (tree parm_packs,
12292 				 int arg_pack_len,
12293 				 bool has_empty_arg)
12294 {
12295   /* If one pack has an expansion and another pack has a normal
12296      argument or if one pack has an empty argument and an another
12297      one hasn't then tsubst_pack_expansion cannot perform the
12298      substitution and need to fall back on the
12299      PACK_EXPANSION_EXTRA mechanism.  */
12300   if (parm_packs == NULL_TREE)
12301     return false;
12302   else if (has_empty_arg)
12303     {
12304       /* If all the actual packs are pack expansions, we can still
12305 	 subsitute directly.  */
12306       for (tree p = parm_packs; p; p = TREE_CHAIN (p))
12307 	{
12308 	  tree a = TREE_VALUE (p);
12309 	  if (TREE_CODE (a) == ARGUMENT_PACK_SELECT)
12310 	    a = ARGUMENT_PACK_SELECT_FROM_PACK (a);
12311 	  a = ARGUMENT_PACK_ARGS (a);
12312 	  if (TREE_VEC_LENGTH (a) == 1)
12313 	    a = TREE_VEC_ELT (a, 0);
12314 	  if (PACK_EXPANSION_P (a))
12315 	    continue;
12316 	  return true;
12317 	}
12318       return false;
12319     }
12320 
12321   bool has_expansion_arg = false;
12322   for (int i = 0 ; i < arg_pack_len; ++i)
12323     {
12324       bool has_non_expansion_arg = false;
12325       for (tree parm_pack = parm_packs;
12326 	   parm_pack;
12327 	   parm_pack = TREE_CHAIN (parm_pack))
12328 	{
12329 	  tree arg = TREE_VALUE (parm_pack);
12330 
12331 	  int exp = argument_pack_element_is_expansion_p (arg, i);
12332 	  if (exp == 2)
12333 	    /* We can't substitute a pack expansion with extra args into
12334 	       our pattern.  */
12335 	    return true;
12336 	  else if (exp)
12337 	    has_expansion_arg = true;
12338 	  else
12339 	    has_non_expansion_arg = true;
12340 	}
12341 
12342       if (has_expansion_arg && has_non_expansion_arg)
12343 	return true;
12344     }
12345   return false;
12346 }
12347 
12348 /* [temp.variadic]/6 says that:
12349 
12350        The instantiation of a pack expansion [...]
12351        produces a list E1,E2, ..., En, where N is the number of elements
12352        in the pack expansion parameters.
12353 
12354    This subroutine of tsubst_pack_expansion produces one of these Ei.
12355 
12356    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
12357    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
12358    PATTERN, and each TREE_VALUE is its corresponding argument pack.
12359    INDEX is the index 'i' of the element Ei to produce.  ARGS,
12360    COMPLAIN, and IN_DECL are the same parameters as for the
12361    tsubst_pack_expansion function.
12362 
12363    The function returns the resulting Ei upon successful completion,
12364    or error_mark_node.
12365 
12366    Note that this function possibly modifies the ARGS parameter, so
12367    it's the responsibility of the caller to restore it.  */
12368 
12369 static tree
gen_elem_of_pack_expansion_instantiation(tree pattern,tree parm_packs,unsigned index,tree args,tsubst_flags_t complain,tree in_decl)12370 gen_elem_of_pack_expansion_instantiation (tree pattern,
12371 					  tree parm_packs,
12372 					  unsigned index,
12373 					  tree args /* This parm gets
12374 						       modified.  */,
12375 					  tsubst_flags_t complain,
12376 					  tree in_decl)
12377 {
12378   tree t;
12379   bool ith_elem_is_expansion = false;
12380 
12381   /* For each parameter pack, change the substitution of the parameter
12382      pack to the ith argument in its argument pack, then expand the
12383      pattern.  */
12384   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
12385     {
12386       tree parm = TREE_PURPOSE (pack);
12387       tree arg_pack = TREE_VALUE (pack);
12388       tree aps;			/* instance of ARGUMENT_PACK_SELECT.  */
12389 
12390       ith_elem_is_expansion |=
12391 	argument_pack_element_is_expansion_p (arg_pack, index);
12392 
12393       /* Select the Ith argument from the pack.  */
12394       if (TREE_CODE (parm) == PARM_DECL
12395 	  || VAR_P (parm)
12396 	  || TREE_CODE (parm) == FIELD_DECL)
12397 	{
12398 	  if (index == 0)
12399 	    {
12400 	      aps = make_argument_pack_select (arg_pack, index);
12401 	      if (!mark_used (parm, complain) && !(complain & tf_error))
12402 		return error_mark_node;
12403 	      register_local_specialization (aps, parm);
12404 	    }
12405 	  else
12406 	    aps = retrieve_local_specialization (parm);
12407 	}
12408       else
12409 	{
12410 	  int idx, level;
12411 	  template_parm_level_and_index (parm, &level, &idx);
12412 
12413 	  if (index == 0)
12414 	    {
12415 	      aps = make_argument_pack_select (arg_pack, index);
12416 	      /* Update the corresponding argument.  */
12417 	      TMPL_ARG (args, level, idx) = aps;
12418 	    }
12419 	  else
12420 	    /* Re-use the ARGUMENT_PACK_SELECT.  */
12421 	    aps = TMPL_ARG (args, level, idx);
12422 	}
12423       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
12424     }
12425 
12426   /* Substitute into the PATTERN with the (possibly altered)
12427      arguments.  */
12428   if (pattern == in_decl)
12429     /* Expanding a fixed parameter pack from
12430        coerce_template_parameter_pack.  */
12431     t = tsubst_decl (pattern, args, complain);
12432   else if (pattern == error_mark_node)
12433     t = error_mark_node;
12434   else if (!TYPE_P (pattern))
12435     t = tsubst_expr (pattern, args, complain, in_decl,
12436 		     /*integral_constant_expression_p=*/false);
12437   else
12438     t = tsubst (pattern, args, complain, in_decl);
12439 
12440   /*  If the Ith argument pack element is a pack expansion, then
12441       the Ith element resulting from the substituting is going to
12442       be a pack expansion as well.  */
12443   if (ith_elem_is_expansion)
12444     t = make_pack_expansion (t, complain);
12445 
12446   return t;
12447 }
12448 
12449 /* When the unexpanded parameter pack in a fold expression expands to an empty
12450    sequence, the value of the expression is as follows; the program is
12451    ill-formed if the operator is not listed in this table.
12452 
12453    &&	true
12454    ||	false
12455    ,	void()  */
12456 
12457 tree
expand_empty_fold(tree t,tsubst_flags_t complain)12458 expand_empty_fold (tree t, tsubst_flags_t complain)
12459 {
12460   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
12461   if (!FOLD_EXPR_MODIFY_P (t))
12462     switch (code)
12463       {
12464       case TRUTH_ANDIF_EXPR:
12465 	return boolean_true_node;
12466       case TRUTH_ORIF_EXPR:
12467 	return boolean_false_node;
12468       case COMPOUND_EXPR:
12469 	return void_node;
12470       default:
12471 	break;
12472       }
12473 
12474   if (complain & tf_error)
12475     error_at (location_of (t),
12476 	      "fold of empty expansion over %O", code);
12477   return error_mark_node;
12478 }
12479 
12480 /* Given a fold-expression T and a current LEFT and RIGHT operand,
12481    form an expression that combines the two terms using the
12482    operator of T. */
12483 
12484 static tree
fold_expression(tree t,tree left,tree right,tsubst_flags_t complain)12485 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
12486 {
12487   tree op = FOLD_EXPR_OP (t);
12488   tree_code code = (tree_code)TREE_INT_CST_LOW (op);
12489 
12490   // Handle compound assignment operators.
12491   if (FOLD_EXPR_MODIFY_P (t))
12492     return build_x_modify_expr (input_location, left, code, right, complain);
12493 
12494   warning_sentinel s(warn_parentheses);
12495   switch (code)
12496     {
12497     case COMPOUND_EXPR:
12498       return build_x_compound_expr (input_location, left, right, complain);
12499     default:
12500       return build_x_binary_op (input_location, code,
12501                                 left, TREE_CODE (left),
12502                                 right, TREE_CODE (right),
12503                                 /*overload=*/NULL,
12504                                 complain);
12505     }
12506 }
12507 
12508 /* Substitute ARGS into the pack of a fold expression T. */
12509 
12510 static inline tree
tsubst_fold_expr_pack(tree t,tree args,tsubst_flags_t complain,tree in_decl)12511 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12512 {
12513   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
12514 }
12515 
12516 /* Substitute ARGS into the pack of a fold expression T. */
12517 
12518 static inline tree
tsubst_fold_expr_init(tree t,tree args,tsubst_flags_t complain,tree in_decl)12519 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12520 {
12521   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
12522 }
12523 
12524 /* Expand a PACK of arguments into a grouped as left fold.
12525    Given a pack containing elements A0, A1, ..., An and an
12526    operator @, this builds the expression:
12527 
12528       ((A0 @ A1) @ A2) ... @ An
12529 
12530    Note that PACK must not be empty.
12531 
12532    The operator is defined by the original fold expression T. */
12533 
12534 static tree
expand_left_fold(tree t,tree pack,tsubst_flags_t complain)12535 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
12536 {
12537   tree left = TREE_VEC_ELT (pack, 0);
12538   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
12539     {
12540       tree right = TREE_VEC_ELT (pack, i);
12541       left = fold_expression (t, left, right, complain);
12542     }
12543   return left;
12544 }
12545 
12546 /* Substitute into a unary left fold expression. */
12547 
12548 static tree
tsubst_unary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12549 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
12550                         tree in_decl)
12551 {
12552   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12553   if (pack == error_mark_node)
12554     return error_mark_node;
12555   if (PACK_EXPANSION_P (pack))
12556     {
12557       tree r = copy_node (t);
12558       FOLD_EXPR_PACK (r) = pack;
12559       return r;
12560     }
12561   if (TREE_VEC_LENGTH (pack) == 0)
12562     return expand_empty_fold (t, complain);
12563   else
12564     return expand_left_fold (t, pack, complain);
12565 }
12566 
12567 /* Substitute into a binary left fold expression.
12568 
12569    Do ths by building a single (non-empty) vector of argumnts and
12570    building the expression from those elements. */
12571 
12572 static tree
tsubst_binary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12573 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
12574                          tree in_decl)
12575 {
12576   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12577   if (pack == error_mark_node)
12578     return error_mark_node;
12579   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12580   if (init == error_mark_node)
12581     return error_mark_node;
12582 
12583   if (PACK_EXPANSION_P (pack))
12584     {
12585       tree r = copy_node (t);
12586       FOLD_EXPR_PACK (r) = pack;
12587       FOLD_EXPR_INIT (r) = init;
12588       return r;
12589     }
12590 
12591   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
12592   TREE_VEC_ELT (vec, 0) = init;
12593   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
12594     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
12595 
12596   return expand_left_fold (t, vec, complain);
12597 }
12598 
12599 /* Expand a PACK of arguments into a grouped as right fold.
12600    Given a pack containing elementns A0, A1, ..., and an
12601    operator @, this builds the expression:
12602 
12603       A0@ ... (An-2 @ (An-1 @ An))
12604 
12605    Note that PACK must not be empty.
12606 
12607    The operator is defined by the original fold expression T. */
12608 
12609 tree
expand_right_fold(tree t,tree pack,tsubst_flags_t complain)12610 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
12611 {
12612   // Build the expression.
12613   int n = TREE_VEC_LENGTH (pack);
12614   tree right = TREE_VEC_ELT (pack, n - 1);
12615   for (--n; n != 0; --n)
12616     {
12617       tree left = TREE_VEC_ELT (pack, n - 1);
12618       right = fold_expression (t, left, right, complain);
12619     }
12620   return right;
12621 }
12622 
12623 /* Substitute into a unary right fold expression. */
12624 
12625 static tree
tsubst_unary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12626 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
12627                          tree in_decl)
12628 {
12629   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12630   if (pack == error_mark_node)
12631     return error_mark_node;
12632   if (PACK_EXPANSION_P (pack))
12633     {
12634       tree r = copy_node (t);
12635       FOLD_EXPR_PACK (r) = pack;
12636       return r;
12637     }
12638   if (TREE_VEC_LENGTH (pack) == 0)
12639     return expand_empty_fold (t, complain);
12640   else
12641     return expand_right_fold (t, pack, complain);
12642 }
12643 
12644 /* Substitute into a binary right fold expression.
12645 
12646    Do ths by building a single (non-empty) vector of arguments and
12647    building the expression from those elements. */
12648 
12649 static tree
tsubst_binary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)12650 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
12651                          tree in_decl)
12652 {
12653   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
12654   if (pack == error_mark_node)
12655     return error_mark_node;
12656   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
12657   if (init == error_mark_node)
12658     return error_mark_node;
12659 
12660   if (PACK_EXPANSION_P (pack))
12661     {
12662       tree r = copy_node (t);
12663       FOLD_EXPR_PACK (r) = pack;
12664       FOLD_EXPR_INIT (r) = init;
12665       return r;
12666     }
12667 
12668   int n = TREE_VEC_LENGTH (pack);
12669   tree vec = make_tree_vec (n + 1);
12670   for (int i = 0; i < n; ++i)
12671     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
12672   TREE_VEC_ELT (vec, n) = init;
12673 
12674   return expand_right_fold (t, vec, complain);
12675 }
12676 
12677 /* Walk through the pattern of a pack expansion, adding everything in
12678    local_specializations to a list.  */
12679 
12680 class el_data
12681 {
12682 public:
12683   /* Set of variables declared within the pattern.  */
12684   hash_set<tree> internal;
12685   /* Set of AST nodes that have been visited by the traversal.  */
12686   hash_set<tree> visited;
12687   /* List of local_specializations used within the pattern.  */
12688   tree extra;
12689   tsubst_flags_t complain;
12690 
el_data(tsubst_flags_t c)12691   el_data (tsubst_flags_t c)
12692     : extra (NULL_TREE), complain (c) {}
12693 };
12694 static tree
extract_locals_r(tree * tp,int *,void * data_)12695 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
12696 {
12697   el_data &data = *reinterpret_cast<el_data*>(data_);
12698   tree *extra = &data.extra;
12699   tsubst_flags_t complain = data.complain;
12700 
12701   if (TYPE_P (*tp) && typedef_variant_p (*tp))
12702     /* Remember local typedefs (85214).  */
12703     tp = &TYPE_NAME (*tp);
12704 
12705   if (TREE_CODE (*tp) == DECL_EXPR)
12706     {
12707       tree decl = DECL_EXPR_DECL (*tp);
12708       data.internal.add (decl);
12709       if (VAR_P (decl)
12710 	  && DECL_DECOMPOSITION_P (decl)
12711 	  && TREE_TYPE (decl) != error_mark_node)
12712 	{
12713 	  gcc_assert (DECL_NAME (decl) == NULL_TREE);
12714 	  for (tree decl2 = DECL_CHAIN (decl);
12715 	       decl2
12716 	       && VAR_P (decl2)
12717 	       && DECL_DECOMPOSITION_P (decl2)
12718 	       && DECL_NAME (decl2)
12719 	       && TREE_TYPE (decl2) != error_mark_node;
12720 	       decl2 = DECL_CHAIN (decl2))
12721 	    {
12722 	      gcc_assert (DECL_DECOMP_BASE (decl2) == decl);
12723 	      data.internal.add (decl2);
12724 	    }
12725 	}
12726     }
12727   else if (TREE_CODE (*tp) == LAMBDA_EXPR)
12728     {
12729       /* Since we defer implicit capture, look in the parms and body.  */
12730       tree fn = lambda_function (*tp);
12731       cp_walk_tree (&TREE_TYPE (fn), &extract_locals_r, &data,
12732 		    &data.visited);
12733       cp_walk_tree (&DECL_SAVED_TREE (fn), &extract_locals_r, &data,
12734 		    &data.visited);
12735     }
12736   else if (tree spec = retrieve_local_specialization (*tp))
12737     {
12738       if (data.internal.contains (*tp))
12739 	/* Don't mess with variables declared within the pattern.  */
12740 	return NULL_TREE;
12741       if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12742 	{
12743 	  /* Maybe pull out the PARM_DECL for a partial instantiation.  */
12744 	  tree args = ARGUMENT_PACK_ARGS (spec);
12745 	  if (TREE_VEC_LENGTH (args) == 1)
12746 	    {
12747 	      tree elt = TREE_VEC_ELT (args, 0);
12748 	      if (PACK_EXPANSION_P (elt))
12749 		elt = PACK_EXPANSION_PATTERN (elt);
12750 	      if (DECL_PACK_P (elt))
12751 		spec = elt;
12752 	    }
12753 	  if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
12754 	    {
12755 	      /* Handle lambda capture here, since we aren't doing any
12756 		 substitution now, and so tsubst_copy won't call
12757 		 process_outer_var_ref.  */
12758 	      tree args = ARGUMENT_PACK_ARGS (spec);
12759 	      int len = TREE_VEC_LENGTH (args);
12760 	      for (int i = 0; i < len; ++i)
12761 		{
12762 		  tree arg = TREE_VEC_ELT (args, i);
12763 		  tree carg = arg;
12764 		  if (outer_automatic_var_p (arg))
12765 		    carg = process_outer_var_ref (arg, complain);
12766 		  if (carg != arg)
12767 		    {
12768 		      /* Make a new NONTYPE_ARGUMENT_PACK of the capture
12769 			 proxies.  */
12770 		      if (i == 0)
12771 			{
12772 			  spec = copy_node (spec);
12773 			  args = copy_node (args);
12774 			  SET_ARGUMENT_PACK_ARGS (spec, args);
12775 			  register_local_specialization (spec, *tp);
12776 			}
12777 		      TREE_VEC_ELT (args, i) = carg;
12778 		    }
12779 		}
12780 	    }
12781 	}
12782       if (outer_automatic_var_p (spec))
12783 	spec = process_outer_var_ref (spec, complain);
12784       *extra = tree_cons (*tp, spec, *extra);
12785     }
12786   return NULL_TREE;
12787 }
12788 static tree
extract_local_specs(tree pattern,tsubst_flags_t complain)12789 extract_local_specs (tree pattern, tsubst_flags_t complain)
12790 {
12791   el_data data (complain);
12792   cp_walk_tree (&pattern, extract_locals_r, &data, &data.visited);
12793   return data.extra;
12794 }
12795 
12796 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
12797    for use in PACK_EXPANSION_EXTRA_ARGS.  */
12798 
12799 tree
build_extra_args(tree pattern,tree args,tsubst_flags_t complain)12800 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
12801 {
12802   tree extra = args;
12803   if (local_specializations)
12804     if (tree locals = extract_local_specs (pattern, complain))
12805       extra = tree_cons (NULL_TREE, extra, locals);
12806   return extra;
12807 }
12808 
12809 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
12810    normal template args to ARGS.  */
12811 
12812 tree
add_extra_args(tree extra,tree args)12813 add_extra_args (tree extra, tree args)
12814 {
12815   if (extra && TREE_CODE (extra) == TREE_LIST)
12816     {
12817       for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
12818 	{
12819 	  /* The partial instantiation involved local declarations collected in
12820 	     extract_local_specs; map from the general template to our local
12821 	     context.  */
12822 	  tree gen = TREE_PURPOSE (elt);
12823 	  tree inst = TREE_VALUE (elt);
12824 	  if (DECL_P (inst))
12825 	    if (tree local = retrieve_local_specialization (inst))
12826 	      inst = local;
12827 	  /* else inst is already a full instantiation of the pack.  */
12828 	  register_local_specialization (inst, gen);
12829 	}
12830       gcc_assert (!TREE_PURPOSE (extra));
12831       extra = TREE_VALUE (extra);
12832     }
12833 #if 1
12834   /* I think we should always be able to substitute dependent args into the
12835      pattern.  If that turns out to be incorrect in some cases, enable the
12836      alternate code (and add complain/in_decl parms to this function).  */
12837   gcc_checking_assert (!uses_template_parms (extra));
12838 #else
12839   if (!uses_template_parms (extra))
12840     {
12841       gcc_unreachable ();
12842       extra = tsubst_template_args (extra, args, complain, in_decl);
12843       args = add_outermost_template_args (args, extra);
12844     }
12845   else
12846 #endif
12847     args = add_to_template_args (extra, args);
12848   return args;
12849 }
12850 
12851 /* Substitute ARGS into T, which is an pack expansion
12852    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
12853    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
12854    (if only a partial substitution could be performed) or
12855    ERROR_MARK_NODE if there was an error.  */
12856 tree
tsubst_pack_expansion(tree t,tree args,tsubst_flags_t complain,tree in_decl)12857 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
12858 		       tree in_decl)
12859 {
12860   tree pattern;
12861   tree pack, packs = NULL_TREE;
12862   bool unsubstituted_packs = false;
12863   int i, len = -1;
12864   tree result;
12865   bool need_local_specializations = false;
12866   int levels;
12867 
12868   gcc_assert (PACK_EXPANSION_P (t));
12869   pattern = PACK_EXPANSION_PATTERN (t);
12870 
12871   /* Add in any args remembered from an earlier partial instantiation.  */
12872   args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
12873 
12874   levels = TMPL_ARGS_DEPTH (args);
12875 
12876   /* Determine the argument packs that will instantiate the parameter
12877      packs used in the expansion expression. While we're at it,
12878      compute the number of arguments to be expanded and make sure it
12879      is consistent.  */
12880   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
12881        pack = TREE_CHAIN (pack))
12882     {
12883       tree parm_pack = TREE_VALUE (pack);
12884       tree arg_pack = NULL_TREE;
12885       tree orig_arg = NULL_TREE;
12886       int level = 0;
12887 
12888       if (TREE_CODE (parm_pack) == BASES)
12889 	{
12890 	  gcc_assert (parm_pack == pattern);
12891 	  if (BASES_DIRECT (parm_pack))
12892 	    return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
12893 							args, complain,
12894 							in_decl, false),
12895 					   complain);
12896 	  else
12897 	    return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
12898 						 args, complain, in_decl,
12899 						 false), complain);
12900 	}
12901       else if (builtin_pack_call_p (parm_pack))
12902 	{
12903 	  if (parm_pack != pattern)
12904 	    {
12905 	      if (complain & tf_error)
12906 		sorry ("%qE is not the entire pattern of the pack expansion",
12907 		       parm_pack);
12908 	      return error_mark_node;
12909 	    }
12910 	  return expand_builtin_pack_call (parm_pack, args,
12911 					   complain, in_decl);
12912 	}
12913       else if (TREE_CODE (parm_pack) == PARM_DECL)
12914 	{
12915 	  /* We know we have correct local_specializations if this
12916 	     expansion is at function scope, or if we're dealing with a
12917 	     local parameter in a requires expression; for the latter,
12918 	     tsubst_requires_expr set it up appropriately.  */
12919 	  if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
12920 	    arg_pack = retrieve_local_specialization (parm_pack);
12921 	  else
12922 	    /* We can't rely on local_specializations for a parameter
12923 	       name used later in a function declaration (such as in a
12924 	       late-specified return type).  Even if it exists, it might
12925 	       have the wrong value for a recursive call.  */
12926 	    need_local_specializations = true;
12927 
12928 	  if (!arg_pack)
12929 	    {
12930 	      /* This parameter pack was used in an unevaluated context.  Just
12931 		 make a dummy decl, since it's only used for its type.  */
12932 	      ++cp_unevaluated_operand;
12933 	      arg_pack = tsubst_decl (parm_pack, args, complain);
12934 	      --cp_unevaluated_operand;
12935 	      if (arg_pack && DECL_PACK_P (arg_pack))
12936 		/* Partial instantiation of the parm_pack, we can't build
12937 		   up an argument pack yet.  */
12938 		arg_pack = NULL_TREE;
12939 	      else
12940 		arg_pack = make_fnparm_pack (arg_pack);
12941 	    }
12942 	  else if (DECL_PACK_P (arg_pack))
12943 	    /* This argument pack isn't fully instantiated yet.  */
12944 	    arg_pack = NULL_TREE;
12945 	}
12946       else if (is_capture_proxy (parm_pack))
12947 	{
12948 	  arg_pack = retrieve_local_specialization (parm_pack);
12949 	  if (DECL_PACK_P (arg_pack))
12950 	    arg_pack = NULL_TREE;
12951 	}
12952       else
12953         {
12954 	  int idx;
12955           template_parm_level_and_index (parm_pack, &level, &idx);
12956           if (level <= levels)
12957             arg_pack = TMPL_ARG (args, level, idx);
12958 
12959 	  if (arg_pack && TREE_CODE (arg_pack) == TEMPLATE_TYPE_PARM
12960 	      && TEMPLATE_TYPE_PARAMETER_PACK (arg_pack))
12961 	    arg_pack = NULL_TREE;
12962         }
12963 
12964       orig_arg = arg_pack;
12965       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12966 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12967 
12968       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
12969 	/* This can only happen if we forget to expand an argument
12970 	   pack somewhere else. Just return an error, silently.  */
12971 	{
12972 	  result = make_tree_vec (1);
12973 	  TREE_VEC_ELT (result, 0) = error_mark_node;
12974 	  return result;
12975 	}
12976 
12977       if (arg_pack)
12978         {
12979           int my_len =
12980             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
12981 
12982 	  /* Don't bother trying to do a partial substitution with
12983 	     incomplete packs; we'll try again after deduction.  */
12984           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
12985             return t;
12986 
12987           if (len < 0)
12988 	    len = my_len;
12989 	  else if (len != my_len)
12990             {
12991 	      if (!(complain & tf_error))
12992 		/* Fail quietly.  */;
12993               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
12994                 error ("mismatched argument pack lengths while expanding %qT",
12995                        pattern);
12996               else
12997                 error ("mismatched argument pack lengths while expanding %qE",
12998                        pattern);
12999               return error_mark_node;
13000             }
13001 
13002           /* Keep track of the parameter packs and their corresponding
13003              argument packs.  */
13004           packs = tree_cons (parm_pack, arg_pack, packs);
13005           TREE_TYPE (packs) = orig_arg;
13006         }
13007       else
13008 	{
13009 	  /* We can't substitute for this parameter pack.  We use a flag as
13010 	     well as the missing_level counter because function parameter
13011 	     packs don't have a level.  */
13012 	  gcc_assert (processing_template_decl || is_auto (parm_pack));
13013 	  unsubstituted_packs = true;
13014 	}
13015     }
13016 
13017   /* If the expansion is just T..., return the matching argument pack, unless
13018      we need to call convert_from_reference on all the elements.  This is an
13019      important optimization; see c++/68422.  */
13020   if (!unsubstituted_packs
13021       && TREE_PURPOSE (packs) == pattern)
13022     {
13023       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
13024 
13025       /* If the argument pack is a single pack expansion, pull it out.  */
13026       if (TREE_VEC_LENGTH (args) == 1
13027 	  && pack_expansion_args_count (args))
13028 	return TREE_VEC_ELT (args, 0);
13029 
13030       /* Types need no adjustment, nor does sizeof..., and if we still have
13031 	 some pack expansion args we won't do anything yet.  */
13032       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
13033 	  || PACK_EXPANSION_SIZEOF_P (t)
13034 	  || pack_expansion_args_count (args))
13035 	return args;
13036       /* Also optimize expression pack expansions if we can tell that the
13037 	 elements won't have reference type.  */
13038       tree type = TREE_TYPE (pattern);
13039       if (type && !TYPE_REF_P (type)
13040 	  && !PACK_EXPANSION_P (type)
13041 	  && !WILDCARD_TYPE_P (type))
13042 	return args;
13043       /* Otherwise use the normal path so we get convert_from_reference.  */
13044     }
13045 
13046   /* We cannot expand this expansion expression, because we don't have
13047      all of the argument packs we need.  */
13048   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
13049     {
13050       /* We got some full packs, but we can't substitute them in until we
13051 	 have values for all the packs.  So remember these until then.  */
13052 
13053       t = make_pack_expansion (pattern, complain);
13054       PACK_EXPANSION_EXTRA_ARGS (t)
13055 	= build_extra_args (pattern, args, complain);
13056       return t;
13057     }
13058 
13059   /* If NEED_LOCAL_SPECIALIZATIONS then we're in a late-specified return
13060      type, so create our own local specializations map; the current map is
13061      either NULL or (in the case of recursive unification) might have
13062      bindings that we don't want to use or alter.  */
13063   local_specialization_stack lss (need_local_specializations
13064 				  ? lss_blank : lss_nop);
13065 
13066   if (unsubstituted_packs)
13067     {
13068       /* There were no real arguments, we're just replacing a parameter
13069 	 pack with another version of itself. Substitute into the
13070 	 pattern and return a PACK_EXPANSION_*. The caller will need to
13071 	 deal with that.  */
13072       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
13073 	result = tsubst_expr (pattern, args, complain, in_decl,
13074 			 /*integral_constant_expression_p=*/false);
13075       else
13076 	result = tsubst (pattern, args, complain, in_decl);
13077       result = make_pack_expansion (result, complain);
13078       if (PACK_EXPANSION_AUTO_P (t))
13079 	{
13080 	  /* This is a fake auto... pack expansion created in add_capture with
13081 	     _PACKS that don't appear in the pattern.  Copy one over.  */
13082 	  packs = PACK_EXPANSION_PARAMETER_PACKS (t);
13083 	  pack = retrieve_local_specialization (TREE_VALUE (packs));
13084 	  gcc_checking_assert (DECL_PACK_P (pack));
13085 	  PACK_EXPANSION_PARAMETER_PACKS (result)
13086 	    = build_tree_list (NULL_TREE, pack);
13087 	  PACK_EXPANSION_AUTO_P (result) = true;
13088 	}
13089       return result;
13090     }
13091 
13092   gcc_assert (len >= 0);
13093 
13094   /* For each argument in each argument pack, substitute into the
13095      pattern.  */
13096   result = make_tree_vec (len);
13097   tree elem_args = copy_template_args (args);
13098   for (i = 0; i < len; ++i)
13099     {
13100       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
13101 						    i,
13102 						    elem_args, complain,
13103 						    in_decl);
13104       TREE_VEC_ELT (result, i) = t;
13105       if (t == error_mark_node)
13106 	{
13107 	  result = error_mark_node;
13108 	  break;
13109 	}
13110     }
13111 
13112   /* Update ARGS to restore the substitution from parameter packs to
13113      their argument packs.  */
13114   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13115     {
13116       tree parm = TREE_PURPOSE (pack);
13117 
13118       if (TREE_CODE (parm) == PARM_DECL
13119 	  || VAR_P (parm)
13120 	  || TREE_CODE (parm) == FIELD_DECL)
13121         register_local_specialization (TREE_TYPE (pack), parm);
13122       else
13123         {
13124           int idx, level;
13125 
13126 	  if (TREE_VALUE (pack) == NULL_TREE)
13127 	    continue;
13128 
13129           template_parm_level_and_index (parm, &level, &idx);
13130 
13131           /* Update the corresponding argument.  */
13132           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
13133             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
13134               TREE_TYPE (pack);
13135           else
13136             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
13137         }
13138     }
13139 
13140   /* If the dependent pack arguments were such that we end up with only a
13141      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
13142   if (len == 1 && TREE_CODE (result) == TREE_VEC
13143       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
13144     return TREE_VEC_ELT (result, 0);
13145 
13146   return result;
13147 }
13148 
13149 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
13150    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
13151    parameter packs; all parms generated from a function parameter pack will
13152    have the same DECL_PARM_INDEX.  */
13153 
13154 tree
get_pattern_parm(tree parm,tree tmpl)13155 get_pattern_parm (tree parm, tree tmpl)
13156 {
13157   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
13158   tree patparm;
13159 
13160   if (DECL_ARTIFICIAL (parm))
13161     {
13162       for (patparm = DECL_ARGUMENTS (pattern);
13163 	   patparm; patparm = DECL_CHAIN (patparm))
13164 	if (DECL_ARTIFICIAL (patparm)
13165 	    && DECL_NAME (parm) == DECL_NAME (patparm))
13166 	  break;
13167     }
13168   else
13169     {
13170       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
13171       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
13172       gcc_assert (DECL_PARM_INDEX (patparm)
13173 		  == DECL_PARM_INDEX (parm));
13174     }
13175 
13176   return patparm;
13177 }
13178 
13179 /* Make an argument pack out of the TREE_VEC VEC.  */
13180 
13181 static tree
make_argument_pack(tree vec)13182 make_argument_pack (tree vec)
13183 {
13184   tree pack;
13185   tree elt = TREE_VEC_ELT (vec, 0);
13186   if (TYPE_P (elt))
13187     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
13188   else
13189     {
13190       pack = make_node (NONTYPE_ARGUMENT_PACK);
13191       TREE_CONSTANT (pack) = 1;
13192     }
13193   SET_ARGUMENT_PACK_ARGS (pack, vec);
13194   return pack;
13195 }
13196 
13197 /* Return an exact copy of template args T that can be modified
13198    independently.  */
13199 
13200 static tree
copy_template_args(tree t)13201 copy_template_args (tree t)
13202 {
13203   if (t == error_mark_node)
13204     return t;
13205 
13206   int len = TREE_VEC_LENGTH (t);
13207   tree new_vec = make_tree_vec (len);
13208 
13209   for (int i = 0; i < len; ++i)
13210     {
13211       tree elt = TREE_VEC_ELT (t, i);
13212       if (elt && TREE_CODE (elt) == TREE_VEC)
13213 	elt = copy_template_args (elt);
13214       TREE_VEC_ELT (new_vec, i) = elt;
13215     }
13216 
13217   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
13218     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
13219 
13220   return new_vec;
13221 }
13222 
13223 /* Substitute ARGS into the *_ARGUMENT_PACK orig_arg.  */
13224 
13225 tree
tsubst_argument_pack(tree orig_arg,tree args,tsubst_flags_t complain,tree in_decl)13226 tsubst_argument_pack (tree orig_arg, tree args, tsubst_flags_t complain,
13227 		      tree in_decl)
13228 {
13229   /* Substitute into each of the arguments.  */
13230   tree new_arg = TYPE_P (orig_arg)
13231     ? cxx_make_type (TREE_CODE (orig_arg))
13232     : make_node (TREE_CODE (orig_arg));
13233 
13234   tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
13235 					 args, complain, in_decl);
13236   if (pack_args == error_mark_node)
13237     new_arg = error_mark_node;
13238   else
13239     SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
13240 
13241   if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK)
13242     TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
13243 
13244   return new_arg;
13245 }
13246 
13247 /* Substitute ARGS into the vector or list of template arguments T.  */
13248 
13249 tree
tsubst_template_args(tree t,tree args,tsubst_flags_t complain,tree in_decl)13250 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13251 {
13252   tree orig_t = t;
13253   int len, need_new = 0, i, expanded_len_adjust = 0, out;
13254   tree *elts;
13255 
13256   if (t == error_mark_node)
13257     return error_mark_node;
13258 
13259   len = TREE_VEC_LENGTH (t);
13260   elts = XALLOCAVEC (tree, len);
13261 
13262   for (i = 0; i < len; i++)
13263     {
13264       tree orig_arg = TREE_VEC_ELT (t, i);
13265       tree new_arg;
13266 
13267       if (TREE_CODE (orig_arg) == TREE_VEC)
13268 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
13269       else if (PACK_EXPANSION_P (orig_arg))
13270         {
13271           /* Substitute into an expansion expression.  */
13272           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
13273 
13274           if (TREE_CODE (new_arg) == TREE_VEC)
13275             /* Add to the expanded length adjustment the number of
13276                expanded arguments. We subtract one from this
13277                measurement, because the argument pack expression
13278                itself is already counted as 1 in
13279                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
13280                the argument pack is empty.  */
13281             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
13282         }
13283       else if (ARGUMENT_PACK_P (orig_arg))
13284 	new_arg = tsubst_argument_pack (orig_arg, args, complain, in_decl);
13285       else
13286 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
13287 
13288       if (new_arg == error_mark_node)
13289 	return error_mark_node;
13290 
13291       elts[i] = new_arg;
13292       if (new_arg != orig_arg)
13293 	need_new = 1;
13294     }
13295 
13296   if (!need_new)
13297     return t;
13298 
13299   /* Make space for the expanded arguments coming from template
13300      argument packs.  */
13301   t = make_tree_vec (len + expanded_len_adjust);
13302   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
13303      arguments for a member template.
13304      In that case each TREE_VEC in ORIG_T represents a level of template
13305      arguments, and ORIG_T won't carry any non defaulted argument count.
13306      It will rather be the nested TREE_VECs that will carry one.
13307      In other words, ORIG_T carries a non defaulted argument count only
13308      if it doesn't contain any nested TREE_VEC.  */
13309   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
13310     {
13311       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
13312       count += expanded_len_adjust;
13313       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
13314     }
13315   for (i = 0, out = 0; i < len; i++)
13316     {
13317       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
13318            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
13319           && TREE_CODE (elts[i]) == TREE_VEC)
13320         {
13321           int idx;
13322 
13323           /* Now expand the template argument pack "in place".  */
13324           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
13325             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
13326         }
13327       else
13328         {
13329           TREE_VEC_ELT (t, out) = elts[i];
13330           out++;
13331         }
13332     }
13333 
13334   return t;
13335 }
13336 
13337 /* Substitute ARGS into one level PARMS of template parameters.  */
13338 
13339 static tree
tsubst_template_parms_level(tree parms,tree args,tsubst_flags_t complain)13340 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
13341 {
13342   if (parms == error_mark_node)
13343     return error_mark_node;
13344 
13345   tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
13346 
13347   for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
13348     {
13349       tree tuple = TREE_VEC_ELT (parms, i);
13350 
13351       if (tuple == error_mark_node)
13352 	continue;
13353 
13354       TREE_VEC_ELT (new_vec, i) =
13355 	tsubst_template_parm (tuple, args, complain);
13356     }
13357 
13358   return new_vec;
13359 }
13360 
13361 /* Return the result of substituting ARGS into the template parameters
13362    given by PARMS.  If there are m levels of ARGS and m + n levels of
13363    PARMS, then the result will contain n levels of PARMS.  For
13364    example, if PARMS is `template <class T> template <class U>
13365    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
13366    result will be `template <int*, double, class V>'.  */
13367 
13368 static tree
tsubst_template_parms(tree parms,tree args,tsubst_flags_t complain)13369 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
13370 {
13371   tree r = NULL_TREE;
13372   tree* new_parms;
13373 
13374   /* When substituting into a template, we must set
13375      PROCESSING_TEMPLATE_DECL as the template parameters may be
13376      dependent if they are based on one-another, and the dependency
13377      predicates are short-circuit outside of templates.  */
13378   ++processing_template_decl;
13379 
13380   for (new_parms = &r;
13381        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
13382        new_parms = &(TREE_CHAIN (*new_parms)),
13383 	 parms = TREE_CHAIN (parms))
13384     {
13385       tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
13386 						  args, complain);
13387       *new_parms =
13388 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
13389 			     - TMPL_ARGS_DEPTH (args)),
13390 		   new_vec, NULL_TREE);
13391       TEMPLATE_PARMS_CONSTRAINTS (*new_parms)
13392 	= TEMPLATE_PARMS_CONSTRAINTS (parms);
13393     }
13394 
13395   --processing_template_decl;
13396 
13397   return r;
13398 }
13399 
13400 /* Return the result of substituting ARGS into one template parameter
13401    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
13402    parameter and which TREE_PURPOSE is the default argument of the
13403    template parameter.  */
13404 
13405 static tree
tsubst_template_parm(tree t,tree args,tsubst_flags_t complain)13406 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
13407 {
13408   tree default_value, parm_decl;
13409 
13410   if (args == NULL_TREE
13411       || t == NULL_TREE
13412       || t == error_mark_node)
13413     return t;
13414 
13415   gcc_assert (TREE_CODE (t) == TREE_LIST);
13416 
13417   default_value = TREE_PURPOSE (t);
13418   parm_decl = TREE_VALUE (t);
13419   tree constraint = TEMPLATE_PARM_CONSTRAINTS (t);
13420 
13421   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
13422   if (TREE_CODE (parm_decl) == PARM_DECL
13423       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
13424     parm_decl = error_mark_node;
13425   default_value = tsubst_template_arg (default_value, args,
13426 				       complain, NULL_TREE);
13427   constraint = tsubst_constraint (constraint, args, complain, NULL_TREE);
13428 
13429   tree r = build_tree_list (default_value, parm_decl);
13430   TEMPLATE_PARM_CONSTRAINTS (r) = constraint;
13431   return r;
13432 }
13433 
13434 /* Substitute the ARGS into the indicated aggregate (or enumeration)
13435    type T.  If T is not an aggregate or enumeration type, it is
13436    handled as if by tsubst.  IN_DECL is as for tsubst.  If
13437    ENTERING_SCOPE is nonzero, T is the context for a template which
13438    we are presently tsubst'ing.  Return the substituted value.  */
13439 
13440 static tree
tsubst_aggr_type(tree t,tree args,tsubst_flags_t complain,tree in_decl,int entering_scope)13441 tsubst_aggr_type (tree t,
13442 		  tree args,
13443 		  tsubst_flags_t complain,
13444 		  tree in_decl,
13445 		  int entering_scope)
13446 {
13447   if (t == NULL_TREE)
13448     return NULL_TREE;
13449 
13450   switch (TREE_CODE (t))
13451     {
13452     case RECORD_TYPE:
13453       if (TYPE_PTRMEMFUNC_P (t))
13454 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
13455 
13456       /* Fall through.  */
13457     case ENUMERAL_TYPE:
13458     case UNION_TYPE:
13459       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
13460 	{
13461 	  tree argvec;
13462 	  tree context;
13463 	  tree r;
13464 
13465 	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
13466 	  cp_evaluated ev;
13467 
13468 	  /* First, determine the context for the type we are looking
13469 	     up.  */
13470 	  context = TYPE_CONTEXT (t);
13471 	  if (context && TYPE_P (context))
13472 	    {
13473 	      context = tsubst_aggr_type (context, args, complain,
13474 					  in_decl, /*entering_scope=*/1);
13475 	      /* If context is a nested class inside a class template,
13476 	         it may still need to be instantiated (c++/33959).  */
13477 	      context = complete_type (context);
13478 	    }
13479 
13480 	  /* Then, figure out what arguments are appropriate for the
13481 	     type we are trying to find.  For example, given:
13482 
13483 	       template <class T> struct S;
13484 	       template <class T, class U> void f(T, U) { S<U> su; }
13485 
13486 	     and supposing that we are instantiating f<int, double>,
13487 	     then our ARGS will be {int, double}, but, when looking up
13488 	     S we only want {double}.  */
13489 	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
13490 					 complain, in_decl);
13491 	  if (argvec == error_mark_node)
13492 	    r = error_mark_node;
13493 	  else if (!entering_scope
13494 		   && cxx_dialect >= cxx2a && dependent_scope_p (context))
13495 	    {
13496 	      /* See maybe_dependent_member_ref.  */
13497 	      tree name = TYPE_IDENTIFIER (t);
13498 	      tree fullname = name;
13499 	      if (instantiates_primary_template_p (t))
13500 		fullname = build_nt (TEMPLATE_ID_EXPR, name,
13501 				     INNERMOST_TEMPLATE_ARGS (argvec));
13502 	      return build_typename_type (context, name, fullname,
13503 					  typename_type);
13504 	    }
13505 	  else
13506 	    {
13507 	      r = lookup_template_class (t, argvec, in_decl, context,
13508 					 entering_scope, complain);
13509 	      r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
13510 	    }
13511 
13512 	  return r;
13513 	}
13514       else
13515 	/* This is not a template type, so there's nothing to do.  */
13516 	return t;
13517 
13518     default:
13519       return tsubst (t, args, complain, in_decl);
13520     }
13521 }
13522 
13523 static GTY((cache)) decl_tree_cache_map *defarg_inst;
13524 
13525 /* Substitute into the default argument ARG (a default argument for
13526    FN), which has the indicated TYPE.  */
13527 
13528 tree
tsubst_default_argument(tree fn,int parmnum,tree type,tree arg,tsubst_flags_t complain)13529 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
13530 			 tsubst_flags_t complain)
13531 {
13532   int errs = errorcount + sorrycount;
13533 
13534   /* This can happen in invalid code.  */
13535   if (TREE_CODE (arg) == DEFERRED_PARSE)
13536     return arg;
13537 
13538   tree parm = FUNCTION_FIRST_USER_PARM (fn);
13539   parm = chain_index (parmnum, parm);
13540   tree parmtype = TREE_TYPE (parm);
13541   if (DECL_BY_REFERENCE (parm))
13542     parmtype = TREE_TYPE (parmtype);
13543   if (parmtype == error_mark_node)
13544     return error_mark_node;
13545 
13546   gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
13547 
13548   tree *slot;
13549   if (defarg_inst && (slot = defarg_inst->get (parm)))
13550     return *slot;
13551 
13552   /* This default argument came from a template.  Instantiate the
13553      default argument here, not in tsubst.  In the case of
13554      something like:
13555 
13556        template <class T>
13557        struct S {
13558 	 static T t();
13559 	 void f(T = t());
13560        };
13561 
13562      we must be careful to do name lookup in the scope of S<T>,
13563      rather than in the current class.  */
13564   push_to_top_level ();
13565   push_access_scope (fn);
13566   push_deferring_access_checks (dk_no_deferred);
13567   start_lambda_scope (parm);
13568 
13569   /* The default argument expression may cause implicitly defined
13570      member functions to be synthesized, which will result in garbage
13571      collection.  We must treat this situation as if we were within
13572      the body of function so as to avoid collecting live data on the
13573      stack.  */
13574   ++function_depth;
13575   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
13576 		     complain, NULL_TREE,
13577 		     /*integral_constant_expression_p=*/false);
13578   --function_depth;
13579 
13580   finish_lambda_scope ();
13581 
13582   /* Make sure the default argument is reasonable.  */
13583   arg = check_default_argument (type, arg, complain);
13584 
13585   if (errorcount+sorrycount > errs
13586       && (complain & tf_warning_or_error))
13587     inform (input_location,
13588 	    "  when instantiating default argument for call to %qD", fn);
13589 
13590   pop_deferring_access_checks ();
13591   pop_access_scope (fn);
13592   pop_from_top_level ();
13593 
13594   if (arg != error_mark_node && !cp_unevaluated_operand)
13595     {
13596       if (!defarg_inst)
13597 	defarg_inst = decl_tree_cache_map::create_ggc (37);
13598       defarg_inst->put (parm, arg);
13599     }
13600 
13601   return arg;
13602 }
13603 
13604 /* Substitute into all the default arguments for FN.  */
13605 
13606 static void
tsubst_default_arguments(tree fn,tsubst_flags_t complain)13607 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
13608 {
13609   tree arg;
13610   tree tmpl_args;
13611 
13612   tmpl_args = DECL_TI_ARGS (fn);
13613 
13614   /* If this function is not yet instantiated, we certainly don't need
13615      its default arguments.  */
13616   if (uses_template_parms (tmpl_args))
13617     return;
13618   /* Don't do this again for clones.  */
13619   if (DECL_CLONED_FUNCTION_P (fn))
13620     return;
13621 
13622   int i = 0;
13623   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
13624        arg;
13625        arg = TREE_CHAIN (arg), ++i)
13626     if (TREE_PURPOSE (arg))
13627       TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
13628 						    TREE_VALUE (arg),
13629 						    TREE_PURPOSE (arg),
13630 						    complain);
13631 }
13632 
13633 /* Hash table mapping a FUNCTION_DECL to its dependent explicit-specifier.  */
13634 static GTY((cache)) decl_tree_cache_map *explicit_specifier_map;
13635 
13636 /* Store a pair to EXPLICIT_SPECIFIER_MAP.  */
13637 
13638 void
store_explicit_specifier(tree v,tree t)13639 store_explicit_specifier (tree v, tree t)
13640 {
13641   if (!explicit_specifier_map)
13642     explicit_specifier_map = decl_tree_cache_map::create_ggc (37);
13643   DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (v) = true;
13644   explicit_specifier_map->put (v, t);
13645 }
13646 
13647 /* Lookup an element in EXPLICIT_SPECIFIER_MAP.  */
13648 
13649 static tree
lookup_explicit_specifier(tree v)13650 lookup_explicit_specifier (tree v)
13651 {
13652   return *explicit_specifier_map->get (v);
13653 }
13654 
13655 /* Given T, a FUNCTION_TYPE or METHOD_TYPE, construct and return a corresponding
13656    FUNCTION_TYPE or METHOD_TYPE whose return type is RETURN_TYPE, argument types
13657    are ARG_TYPES, and exception specification is RAISES, and otherwise is
13658    identical to T.  */
13659 
13660 static tree
rebuild_function_or_method_type(tree t,tree return_type,tree arg_types,tree raises,tsubst_flags_t complain)13661 rebuild_function_or_method_type (tree t, tree return_type, tree arg_types,
13662 				 tree raises, tsubst_flags_t complain)
13663 {
13664   gcc_assert (FUNC_OR_METHOD_TYPE_P (t));
13665 
13666   tree new_type;
13667   if (TREE_CODE (t) == FUNCTION_TYPE)
13668     {
13669       new_type = build_function_type (return_type, arg_types);
13670       new_type = apply_memfn_quals (new_type, type_memfn_quals (t));
13671     }
13672   else
13673     {
13674       tree r = TREE_TYPE (TREE_VALUE (arg_types));
13675       /* Don't pick up extra function qualifiers from the basetype.  */
13676       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
13677       if (! MAYBE_CLASS_TYPE_P (r))
13678 	{
13679 	  /* [temp.deduct]
13680 
13681 	     Type deduction may fail for any of the following
13682 	     reasons:
13683 
13684 	     -- Attempting to create "pointer to member of T" when T
13685 	     is not a class type.  */
13686 	  if (complain & tf_error)
13687 	    error ("creating pointer to member function of non-class type %qT",
13688 		   r);
13689 	  return error_mark_node;
13690 	}
13691 
13692       new_type = build_method_type_directly (r, return_type,
13693 					     TREE_CHAIN (arg_types));
13694     }
13695   new_type = cp_build_type_attribute_variant (new_type, TYPE_ATTRIBUTES (t));
13696 
13697   cp_ref_qualifier rqual = type_memfn_rqual (t);
13698   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
13699   return build_cp_fntype_variant (new_type, rqual, raises, late_return_type_p);
13700 }
13701 
13702 /* Check if the function type of DECL, a FUNCTION_DECL, agrees with the type of
13703    each of its formal parameters.  If there is a disagreement then rebuild
13704    DECL's function type according to its formal parameter types, as part of a
13705    resolution for Core issues 1001/1322.  */
13706 
13707 static void
maybe_rebuild_function_decl_type(tree decl)13708 maybe_rebuild_function_decl_type (tree decl)
13709 {
13710   bool function_type_needs_rebuilding = false;
13711   if (tree parm_list = FUNCTION_FIRST_USER_PARM (decl))
13712     {
13713       tree parm_type_list = FUNCTION_FIRST_USER_PARMTYPE (decl);
13714       while (parm_type_list && parm_type_list != void_list_node)
13715 	{
13716 	  tree parm_type = TREE_VALUE (parm_type_list);
13717 	  tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
13718 	  if (!same_type_p (parm_type, formal_parm_type_unqual))
13719 	    {
13720 	      function_type_needs_rebuilding = true;
13721 	      break;
13722 	    }
13723 
13724 	  parm_list = DECL_CHAIN (parm_list);
13725 	  parm_type_list = TREE_CHAIN (parm_type_list);
13726 	}
13727     }
13728 
13729   if (!function_type_needs_rebuilding)
13730     return;
13731 
13732   const tree fntype = TREE_TYPE (decl);
13733   tree parm_list = DECL_ARGUMENTS (decl);
13734   tree old_parm_type_list = TYPE_ARG_TYPES (fntype);
13735   tree new_parm_type_list = NULL_TREE;
13736   tree *q = &new_parm_type_list;
13737   for (int skip = num_artificial_parms_for (decl); skip > 0; skip--)
13738     {
13739       *q = copy_node (old_parm_type_list);
13740       parm_list = DECL_CHAIN (parm_list);
13741       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
13742       q = &TREE_CHAIN (*q);
13743     }
13744   while (old_parm_type_list && old_parm_type_list != void_list_node)
13745     {
13746       *q = copy_node (old_parm_type_list);
13747       tree *new_parm_type = &TREE_VALUE (*q);
13748       tree formal_parm_type_unqual = strip_top_quals (TREE_TYPE (parm_list));
13749       if (!same_type_p (*new_parm_type, formal_parm_type_unqual))
13750 	*new_parm_type = formal_parm_type_unqual;
13751 
13752       parm_list = DECL_CHAIN (parm_list);
13753       old_parm_type_list = TREE_CHAIN (old_parm_type_list);
13754       q = &TREE_CHAIN (*q);
13755     }
13756   if (old_parm_type_list == void_list_node)
13757     *q = void_list_node;
13758 
13759   TREE_TYPE (decl)
13760     = rebuild_function_or_method_type (fntype,
13761 				       TREE_TYPE (fntype), new_parm_type_list,
13762 				       TYPE_RAISES_EXCEPTIONS (fntype), tf_none);
13763 }
13764 
13765 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
13766 
13767 static tree
tsubst_function_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)13768 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
13769 		      tree lambda_fntype)
13770 {
13771   tree gen_tmpl, argvec;
13772   hashval_t hash = 0;
13773   tree in_decl = t;
13774 
13775   /* Nobody should be tsubst'ing into non-template functions.  */
13776   gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
13777 
13778   if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
13779     {
13780       /* If T is not dependent, just return it.  */
13781       if (!uses_template_parms (DECL_TI_ARGS (t))
13782 	  && !LAMBDA_FUNCTION_P (t))
13783 	return t;
13784 
13785       /* Calculate the most general template of which R is a
13786 	 specialization.  */
13787       gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
13788 
13789       /* We're substituting a lambda function under tsubst_lambda_expr but not
13790 	 directly from it; find the matching function we're already inside.
13791 	 But don't do this if T is a generic lambda with a single level of
13792 	 template parms, as in that case we're doing a normal instantiation. */
13793       if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
13794 	  && (!generic_lambda_fn_p (t)
13795 	      || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
13796 	return enclosing_instantiation_of (t);
13797 
13798       /* Calculate the complete set of arguments used to
13799 	 specialize R.  */
13800       argvec = tsubst_template_args (DECL_TI_ARGS
13801 				     (DECL_TEMPLATE_RESULT
13802 				      (DECL_TI_TEMPLATE (t))),
13803 				     args, complain, in_decl);
13804       if (argvec == error_mark_node)
13805 	return error_mark_node;
13806 
13807       /* Check to see if we already have this specialization.  */
13808       if (!lambda_fntype)
13809 	{
13810 	  hash = hash_tmpl_and_args (gen_tmpl, argvec);
13811 	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
13812 	    return spec;
13813 	}
13814     }
13815   else
13816     {
13817       /* This special case arises when we have something like this:
13818 
13819 	 template <class T> struct S {
13820 	 friend void f<int>(int, double);
13821 	 };
13822 
13823 	 Here, the DECL_TI_TEMPLATE for the friend declaration
13824 	 will be an IDENTIFIER_NODE.  We are being called from
13825 	 tsubst_friend_function, and we want only to create a
13826 	 new decl (R) with appropriate types so that we can call
13827 	 determine_specialization.  */
13828       gen_tmpl = NULL_TREE;
13829       argvec = NULL_TREE;
13830     }
13831 
13832   tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
13833 		  : NULL_TREE);
13834   tree ctx = closure ? closure : DECL_CONTEXT (t);
13835   bool member = ctx && TYPE_P (ctx);
13836 
13837   if (member && !closure)
13838     ctx = tsubst_aggr_type (ctx, args,
13839 			    complain, t, /*entering_scope=*/1);
13840 
13841   tree type = (lambda_fntype ? lambda_fntype
13842 	       : tsubst (TREE_TYPE (t), args,
13843 			 complain | tf_fndecl_type, in_decl));
13844   if (type == error_mark_node)
13845     return error_mark_node;
13846 
13847   /* If we hit excessive deduction depth, the type is bogus even if
13848      it isn't error_mark_node, so don't build a decl.  */
13849   if (excessive_deduction_depth)
13850     return error_mark_node;
13851 
13852   /* We do NOT check for matching decls pushed separately at this
13853      point, as they may not represent instantiations of this
13854      template, and in any case are considered separate under the
13855      discrete model.  */
13856   tree r = copy_decl (t);
13857   DECL_USE_TEMPLATE (r) = 0;
13858   TREE_TYPE (r) = type;
13859   /* Clear out the mangled name and RTL for the instantiation.  */
13860   SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13861   SET_DECL_RTL (r, NULL);
13862   /* Leave DECL_INITIAL set on deleted instantiations.  */
13863   if (!DECL_DELETED_FN (r))
13864     DECL_INITIAL (r) = NULL_TREE;
13865   DECL_CONTEXT (r) = ctx;
13866 
13867   /* Handle explicit(dependent-expr).  */
13868   if (DECL_HAS_DEPENDENT_EXPLICIT_SPEC_P (t))
13869     {
13870       tree spec = lookup_explicit_specifier (t);
13871       spec = tsubst_copy_and_build (spec, args, complain, in_decl,
13872 				    /*function_p=*/false,
13873 				    /*i_c_e_p=*/true);
13874       spec = build_explicit_specifier (spec, complain);
13875       DECL_NONCONVERTING_P (r) = (spec == boolean_true_node);
13876     }
13877 
13878   /* OpenMP UDRs have the only argument a reference to the declared
13879      type.  We want to diagnose if the declared type is a reference,
13880      which is invalid, but as references to references are usually
13881      quietly merged, diagnose it here.  */
13882   if (DECL_OMP_DECLARE_REDUCTION_P (t))
13883     {
13884       tree argtype
13885 	= TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
13886       argtype = tsubst (argtype, args, complain, in_decl);
13887       if (TYPE_REF_P (argtype))
13888 	error_at (DECL_SOURCE_LOCATION (t),
13889 		  "reference type %qT in "
13890 		  "%<#pragma omp declare reduction%>", argtype);
13891       if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
13892 	DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
13893 					  argtype);
13894     }
13895 
13896   if (member && DECL_CONV_FN_P (r))
13897     /* Type-conversion operator.  Reconstruct the name, in
13898        case it's the name of one of the template's parameters.  */
13899     DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
13900 
13901   tree parms = DECL_ARGUMENTS (t);
13902   if (closure)
13903     parms = DECL_CHAIN (parms);
13904   parms = tsubst (parms, args, complain, t);
13905   for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
13906     DECL_CONTEXT (parm) = r;
13907   if (closure)
13908     {
13909       tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
13910       DECL_CHAIN (tparm) = parms;
13911       parms = tparm;
13912     }
13913   DECL_ARGUMENTS (r) = parms;
13914   DECL_RESULT (r) = NULL_TREE;
13915 
13916   maybe_rebuild_function_decl_type (r);
13917 
13918   TREE_STATIC (r) = 0;
13919   TREE_PUBLIC (r) = TREE_PUBLIC (t);
13920   DECL_EXTERNAL (r) = 1;
13921   /* If this is an instantiation of a function with internal
13922      linkage, we already know what object file linkage will be
13923      assigned to the instantiation.  */
13924   DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
13925   DECL_DEFER_OUTPUT (r) = 0;
13926   DECL_CHAIN (r) = NULL_TREE;
13927   DECL_PENDING_INLINE_INFO (r) = 0;
13928   DECL_PENDING_INLINE_P (r) = 0;
13929   DECL_SAVED_TREE (r) = NULL_TREE;
13930   DECL_STRUCT_FUNCTION (r) = NULL;
13931   TREE_USED (r) = 0;
13932   /* We'll re-clone as appropriate in instantiate_template.  */
13933   DECL_CLONED_FUNCTION (r) = NULL_TREE;
13934 
13935   /* If we aren't complaining now, return on error before we register
13936      the specialization so that we'll complain eventually.  */
13937   if ((complain & tf_error) == 0
13938       && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13939       && !grok_op_properties (r, /*complain=*/false))
13940     return error_mark_node;
13941 
13942   /* Associate the constraints directly with the instantiation. We
13943      don't substitute through the constraints; that's only done when
13944      they are checked.  */
13945   if (tree ci = get_constraints (t))
13946     /* Unless we're regenerating a lambda, in which case we'll set the
13947        lambda's constraints in tsubst_lambda_expr.  */
13948     if (!lambda_fntype)
13949       set_constraints (r, ci);
13950 
13951   if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
13952     SET_DECL_FRIEND_CONTEXT (r,
13953 			     tsubst (DECL_FRIEND_CONTEXT (t),
13954 				     args, complain, in_decl));
13955 
13956   /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
13957      this in the special friend case mentioned above where
13958      GEN_TMPL is NULL.  */
13959   if (gen_tmpl && !closure)
13960     {
13961       DECL_TEMPLATE_INFO (r)
13962 	= build_template_info (gen_tmpl, argvec);
13963       SET_DECL_IMPLICIT_INSTANTIATION (r);
13964 
13965       tree new_r
13966 	= register_specialization (r, gen_tmpl, argvec, false, hash);
13967       if (new_r != r)
13968 	/* We instantiated this while substituting into
13969 	   the type earlier (template/friend54.C).  */
13970 	return new_r;
13971 
13972       /* We're not supposed to instantiate default arguments
13973 	 until they are called, for a template.  But, for a
13974 	 declaration like:
13975 
13976 	 template <class T> void f ()
13977 	 { extern void g(int i = T()); }
13978 
13979 	 we should do the substitution when the template is
13980 	 instantiated.  We handle the member function case in
13981 	 instantiate_class_template since the default arguments
13982 	 might refer to other members of the class.  */
13983       if (!member
13984 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
13985 	  && !uses_template_parms (argvec))
13986 	tsubst_default_arguments (r, complain);
13987     }
13988   else
13989     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13990 
13991   /* Copy the list of befriending classes.  */
13992   for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
13993        *friends;
13994        friends = &TREE_CHAIN (*friends))
13995     {
13996       *friends = copy_node (*friends);
13997       TREE_VALUE (*friends)
13998 	= tsubst (TREE_VALUE (*friends), args, complain, in_decl);
13999     }
14000 
14001   if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
14002     {
14003       maybe_retrofit_in_chrg (r);
14004       if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
14005 	return error_mark_node;
14006       /* If this is an instantiation of a member template, clone it.
14007 	 If it isn't, that'll be handled by
14008 	 clone_constructors_and_destructors.  */
14009       if (PRIMARY_TEMPLATE_P (gen_tmpl))
14010 	clone_function_decl (r, /*update_methods=*/false);
14011     }
14012   else if ((complain & tf_error) != 0
14013 	   && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
14014 	   && !grok_op_properties (r, /*complain=*/true))
14015     return error_mark_node;
14016 
14017   /* Possibly limit visibility based on template args.  */
14018   DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14019   if (DECL_VISIBILITY_SPECIFIED (t))
14020     {
14021       DECL_VISIBILITY_SPECIFIED (r) = 0;
14022       DECL_ATTRIBUTES (r)
14023 	= remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14024     }
14025   determine_visibility (r);
14026   if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
14027       && !processing_template_decl)
14028     defaulted_late_check (r);
14029 
14030   apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14031 				  args, complain, in_decl);
14032   if (flag_openmp)
14033     if (tree attr = lookup_attribute ("omp declare variant base",
14034 				      DECL_ATTRIBUTES (r)))
14035       omp_declare_variant_finalize (r, attr);
14036 
14037   return r;
14038 }
14039 
14040 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
14041 
14042 static tree
tsubst_template_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)14043 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
14044 		      tree lambda_fntype)
14045 {
14046   /* We can get here when processing a member function template,
14047      member class template, or template template parameter.  */
14048   tree decl = DECL_TEMPLATE_RESULT (t);
14049   tree in_decl = t;
14050   tree spec;
14051   tree tmpl_args;
14052   tree full_args;
14053   tree r;
14054   hashval_t hash = 0;
14055 
14056   if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14057     {
14058       /* Template template parameter is treated here.  */
14059       tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14060       if (new_type == error_mark_node)
14061 	r = error_mark_node;
14062       /* If we get a real template back, return it.  This can happen in
14063 	 the context of most_specialized_partial_spec.  */
14064       else if (TREE_CODE (new_type) == TEMPLATE_DECL)
14065 	r = new_type;
14066       else
14067 	/* The new TEMPLATE_DECL was built in
14068 	   reduce_template_parm_level.  */
14069 	r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
14070       return r;
14071     }
14072 
14073   if (!lambda_fntype)
14074     {
14075       /* We might already have an instance of this template.
14076 	 The ARGS are for the surrounding class type, so the
14077 	 full args contain the tsubst'd args for the context,
14078 	 plus the innermost args from the template decl.  */
14079       tmpl_args = DECL_CLASS_TEMPLATE_P (t)
14080 	? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
14081 	: DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
14082       /* Because this is a template, the arguments will still be
14083 	 dependent, even after substitution.  If
14084 	 PROCESSING_TEMPLATE_DECL is not set, the dependency
14085 	 predicates will short-circuit.  */
14086       ++processing_template_decl;
14087       full_args = tsubst_template_args (tmpl_args, args,
14088 					complain, in_decl);
14089       --processing_template_decl;
14090       if (full_args == error_mark_node)
14091 	return error_mark_node;
14092 
14093       /* If this is a default template template argument,
14094 	 tsubst might not have changed anything.  */
14095       if (full_args == tmpl_args)
14096 	return t;
14097 
14098       hash = hash_tmpl_and_args (t, full_args);
14099       spec = retrieve_specialization (t, full_args, hash);
14100       if (spec != NULL_TREE)
14101 	{
14102 	  if (TYPE_P (spec))
14103 	    /* Type partial instantiations are stored as the type by
14104 	       lookup_template_class_1, not here as the template.  */
14105 	    spec = CLASSTYPE_TI_TEMPLATE (spec);
14106 	  return spec;
14107 	}
14108     }
14109 
14110   /* Make a new template decl.  It will be similar to the
14111      original, but will record the current template arguments.
14112      We also create a new function declaration, which is just
14113      like the old one, but points to this new template, rather
14114      than the old one.  */
14115   r = copy_decl (t);
14116   gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
14117   DECL_CHAIN (r) = NULL_TREE;
14118 
14119   // Build new template info linking to the original template decl.
14120   if (!lambda_fntype)
14121     {
14122       DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14123       SET_DECL_IMPLICIT_INSTANTIATION (r);
14124     }
14125   else
14126     DECL_TEMPLATE_INFO (r) = NULL_TREE;
14127 
14128   /* The template parameters for this new template are all the
14129      template parameters for the old template, except the
14130      outermost level of parameters.  */
14131   DECL_TEMPLATE_PARMS (r)
14132     = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
14133 			     complain);
14134 
14135   if (TREE_CODE (decl) == TYPE_DECL
14136       && !TYPE_DECL_ALIAS_P (decl))
14137     {
14138       tree new_type;
14139       ++processing_template_decl;
14140       if (CLASS_TYPE_P (TREE_TYPE (t)))
14141 	new_type = tsubst_aggr_type (TREE_TYPE (t), args, complain,
14142 				     in_decl, /*entering*/1);
14143       else
14144 	new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14145       --processing_template_decl;
14146       if (new_type == error_mark_node)
14147 	return error_mark_node;
14148 
14149       TREE_TYPE (r) = new_type;
14150       /* For a partial specialization, we need to keep pointing to
14151 	 the primary template.  */
14152       if (!DECL_TEMPLATE_SPECIALIZATION (t))
14153 	CLASSTYPE_TI_TEMPLATE (new_type) = r;
14154       DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
14155       DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
14156       DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
14157     }
14158   else
14159     {
14160       tree new_decl;
14161       ++processing_template_decl;
14162       if (TREE_CODE (decl) == FUNCTION_DECL)
14163 	new_decl = tsubst_function_decl (decl, args, complain, lambda_fntype);
14164       else
14165 	new_decl = tsubst (decl, args, complain, in_decl);
14166       --processing_template_decl;
14167       if (new_decl == error_mark_node)
14168 	return error_mark_node;
14169 
14170       DECL_TEMPLATE_RESULT (r) = new_decl;
14171       TREE_TYPE (r) = TREE_TYPE (new_decl);
14172       DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
14173       if (lambda_fntype)
14174 	{
14175 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
14176 	  DECL_TEMPLATE_INFO (new_decl) = build_template_info (r, args);
14177 	}
14178       else
14179 	{
14180 	  DECL_TI_TEMPLATE (new_decl) = r;
14181 	  DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
14182 	}
14183     }
14184 
14185   DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
14186   DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
14187 
14188   if (PRIMARY_TEMPLATE_P (t))
14189     DECL_PRIMARY_TEMPLATE (r) = r;
14190 
14191   if (TREE_CODE (decl) != TYPE_DECL && !VAR_P (decl)
14192       && !lambda_fntype)
14193     /* Record this non-type partial instantiation.  */
14194     register_specialization (r, t,
14195 			     DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
14196 			     false, hash);
14197 
14198   return r;
14199 }
14200 
14201 /* True if FN is the op() for a lambda in an uninstantiated template.  */
14202 
14203 bool
lambda_fn_in_template_p(tree fn)14204 lambda_fn_in_template_p (tree fn)
14205 {
14206   if (!fn || !LAMBDA_FUNCTION_P (fn))
14207     return false;
14208   tree closure = DECL_CONTEXT (fn);
14209   return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
14210 }
14211 
14212 /* True if FN is the substitution (via tsubst_lambda_expr) of a function for
14213    which the above is true.  */
14214 
14215 bool
instantiated_lambda_fn_p(tree fn)14216 instantiated_lambda_fn_p (tree fn)
14217 {
14218   if (!fn || !LAMBDA_FUNCTION_P (fn))
14219     return false;
14220   tree closure = DECL_CONTEXT (fn);
14221   tree lam = CLASSTYPE_LAMBDA_EXPR (closure);
14222   return LAMBDA_EXPR_INSTANTIATED (lam);
14223 }
14224 
14225 /* We're instantiating a variable from template function TCTX.  Return the
14226    corresponding current enclosing scope.  This gets complicated because lambda
14227    functions in templates are regenerated rather than instantiated, but generic
14228    lambda functions are subsequently instantiated.  */
14229 
14230 static tree
enclosing_instantiation_of(tree otctx)14231 enclosing_instantiation_of (tree otctx)
14232 {
14233   tree tctx = otctx;
14234   tree fn = current_function_decl;
14235   int lambda_count = 0;
14236 
14237   for (; tctx && (lambda_fn_in_template_p (tctx)
14238 		  || instantiated_lambda_fn_p (tctx));
14239        tctx = decl_function_context (tctx))
14240     ++lambda_count;
14241 
14242   if (!tctx)
14243     {
14244       /* Match using DECL_SOURCE_LOCATION, which is unique for all lambdas.
14245 
14246 	 For GCC 11 the above condition limits this to the previously failing
14247 	 case where all enclosing functions are lambdas (95870).  FIXME.  */
14248       for (tree ofn = fn; ofn; ofn = decl_function_context (ofn))
14249 	if (DECL_SOURCE_LOCATION (ofn) == DECL_SOURCE_LOCATION (otctx))
14250 	  return ofn;
14251       gcc_unreachable ();
14252     }
14253 
14254   for (; fn; fn = decl_function_context (fn))
14255     {
14256       tree ofn = fn;
14257       int flambda_count = 0;
14258       for (; fn && instantiated_lambda_fn_p (fn);
14259 	   fn = decl_function_context (fn))
14260 	++flambda_count;
14261       if ((fn && DECL_TEMPLATE_INFO (fn))
14262 	  ? most_general_template (fn) != most_general_template (tctx)
14263 	  : fn != tctx)
14264 	continue;
14265       if (flambda_count != lambda_count)
14266 	{
14267 	  gcc_assert (flambda_count > lambda_count);
14268 	  for (; flambda_count > lambda_count; --flambda_count)
14269 	    ofn = decl_function_context (ofn);
14270 	}
14271       gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
14272 		  || DECL_CONV_FN_P (ofn));
14273       return ofn;
14274     }
14275   gcc_unreachable ();
14276 }
14277 
14278 /* Substitute the ARGS into the T, which is a _DECL.  Return the
14279    result of the substitution.  Issue error and warning messages under
14280    control of COMPLAIN.  */
14281 
14282 static tree
tsubst_decl(tree t,tree args,tsubst_flags_t complain)14283 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
14284 {
14285 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
14286   location_t saved_loc;
14287   tree r = NULL_TREE;
14288   tree in_decl = t;
14289   hashval_t hash = 0;
14290 
14291   /* Set the filename and linenumber to improve error-reporting.  */
14292   saved_loc = input_location;
14293   input_location = DECL_SOURCE_LOCATION (t);
14294 
14295   switch (TREE_CODE (t))
14296     {
14297     case TEMPLATE_DECL:
14298       r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
14299       break;
14300 
14301     case FUNCTION_DECL:
14302       r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
14303       break;
14304 
14305     case PARM_DECL:
14306       {
14307 	tree type = NULL_TREE;
14308         int i, len = 1;
14309         tree expanded_types = NULL_TREE;
14310         tree prev_r = NULL_TREE;
14311         tree first_r = NULL_TREE;
14312 
14313         if (DECL_PACK_P (t))
14314           {
14315             /* If there is a local specialization that isn't a
14316                parameter pack, it means that we're doing a "simple"
14317                substitution from inside tsubst_pack_expansion. Just
14318                return the local specialization (which will be a single
14319                parm).  */
14320             tree spec = retrieve_local_specialization (t);
14321             if (spec
14322                 && TREE_CODE (spec) == PARM_DECL
14323                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
14324               RETURN (spec);
14325 
14326             /* Expand the TYPE_PACK_EXPANSION that provides the types for
14327                the parameters in this function parameter pack.  */
14328             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14329 						    complain, in_decl);
14330             if (TREE_CODE (expanded_types) == TREE_VEC)
14331               {
14332                 len = TREE_VEC_LENGTH (expanded_types);
14333 
14334                 /* Zero-length parameter packs are boring. Just substitute
14335                    into the chain.  */
14336 		if (len == 0 && !cp_unevaluated_operand)
14337                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
14338 				  TREE_CHAIN (t)));
14339               }
14340             else
14341               {
14342                 /* All we did was update the type. Make a note of that.  */
14343                 type = expanded_types;
14344                 expanded_types = NULL_TREE;
14345               }
14346           }
14347 
14348         /* Loop through all of the parameters we'll build. When T is
14349            a function parameter pack, LEN is the number of expanded
14350            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
14351         r = NULL_TREE;
14352         for (i = 0; i < len; ++i)
14353           {
14354             prev_r = r;
14355             r = copy_node (t);
14356             if (DECL_TEMPLATE_PARM_P (t))
14357               SET_DECL_TEMPLATE_PARM_P (r);
14358 
14359             if (expanded_types)
14360               /* We're on the Ith parameter of the function parameter
14361                  pack.  */
14362               {
14363                 /* Get the Ith type.  */
14364                 type = TREE_VEC_ELT (expanded_types, i);
14365 
14366 		/* Rename the parameter to include the index.  */
14367 		DECL_NAME (r)
14368 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
14369               }
14370             else if (!type)
14371               /* We're dealing with a normal parameter.  */
14372               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14373 
14374             type = type_decays_to (type);
14375             TREE_TYPE (r) = type;
14376             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14377 
14378             if (DECL_INITIAL (r))
14379               {
14380                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
14381                   DECL_INITIAL (r) = TREE_TYPE (r);
14382                 else
14383                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
14384                                              complain, in_decl);
14385               }
14386 
14387             DECL_CONTEXT (r) = NULL_TREE;
14388 
14389             if (!DECL_TEMPLATE_PARM_P (r))
14390               DECL_ARG_TYPE (r) = type_passed_as (type);
14391 
14392 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14393 					    args, complain, in_decl);
14394 
14395             /* Keep track of the first new parameter we
14396                generate. That's what will be returned to the
14397                caller.  */
14398             if (!first_r)
14399               first_r = r;
14400 
14401             /* Build a proper chain of parameters when substituting
14402                into a function parameter pack.  */
14403             if (prev_r)
14404               DECL_CHAIN (prev_r) = r;
14405           }
14406 
14407 	/* If cp_unevaluated_operand is set, we're just looking for a
14408 	   single dummy parameter, so don't keep going.  */
14409 	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
14410 	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
14411 				   complain, DECL_CHAIN (t));
14412 
14413         /* FIRST_R contains the start of the chain we've built.  */
14414         r = first_r;
14415       }
14416       break;
14417 
14418     case FIELD_DECL:
14419       {
14420 	tree type = NULL_TREE;
14421 	tree vec = NULL_TREE;
14422 	tree expanded_types = NULL_TREE;
14423 	int len = 1;
14424 
14425 	if (PACK_EXPANSION_P (TREE_TYPE (t)))
14426 	  {
14427 	    /* This field is a lambda capture pack.  Return a TREE_VEC of
14428 	       the expanded fields to instantiate_class_template_1.  */
14429             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
14430 						    complain, in_decl);
14431             if (TREE_CODE (expanded_types) == TREE_VEC)
14432               {
14433                 len = TREE_VEC_LENGTH (expanded_types);
14434 		vec = make_tree_vec (len);
14435               }
14436             else
14437               {
14438                 /* All we did was update the type. Make a note of that.  */
14439                 type = expanded_types;
14440                 expanded_types = NULL_TREE;
14441               }
14442 	  }
14443 
14444 	for (int i = 0; i < len; ++i)
14445 	  {
14446 	    r = copy_decl (t);
14447 	    if (expanded_types)
14448 	      {
14449 		type = TREE_VEC_ELT (expanded_types, i);
14450 		DECL_NAME (r)
14451 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
14452 	      }
14453             else if (!type)
14454               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14455 
14456 	    if (type == error_mark_node)
14457 	      RETURN (error_mark_node);
14458 	    TREE_TYPE (r) = type;
14459 	    cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14460 
14461 	    if (DECL_C_BIT_FIELD (r))
14462 	      /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
14463 		 number of bits.  */
14464 	      DECL_BIT_FIELD_REPRESENTATIVE (r)
14465 		= tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
14466 			       complain, in_decl,
14467 			       /*integral_constant_expression_p=*/true);
14468 	    if (DECL_INITIAL (t))
14469 	      {
14470 		/* Set up DECL_TEMPLATE_INFO so that we can get at the
14471 		   NSDMI in perform_member_init.  Still set DECL_INITIAL
14472 		   so that we know there is one.  */
14473 		DECL_INITIAL (r) = void_node;
14474 		gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
14475 		retrofit_lang_decl (r);
14476 		DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
14477 	      }
14478 	    /* We don't have to set DECL_CONTEXT here; it is set by
14479 	       finish_member_declaration.  */
14480 	    DECL_CHAIN (r) = NULL_TREE;
14481 
14482 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
14483 					    args, complain, in_decl);
14484 
14485 	    if (vec)
14486 	      TREE_VEC_ELT (vec, i) = r;
14487 	  }
14488 
14489 	if (vec)
14490 	  r = vec;
14491       }
14492       break;
14493 
14494     case USING_DECL:
14495       /* We reach here only for member using decls.  We also need to check
14496 	 uses_template_parms because DECL_DEPENDENT_P is not set for a
14497 	 using-declaration that designates a member of the current
14498 	 instantiation (c++/53549).  */
14499       if (DECL_DEPENDENT_P (t)
14500 	  || uses_template_parms (USING_DECL_SCOPE (t)))
14501 	{
14502 	  tree scope = USING_DECL_SCOPE (t);
14503 	  tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
14504 	  if (PACK_EXPANSION_P (scope))
14505 	    {
14506 	      tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
14507 	      int len = TREE_VEC_LENGTH (vec);
14508 	      r = make_tree_vec (len);
14509 	      for (int i = 0; i < len; ++i)
14510 		{
14511 		  tree escope = TREE_VEC_ELT (vec, i);
14512 		  tree elt = do_class_using_decl (escope, name);
14513 		  if (!elt)
14514 		    {
14515 		      r = error_mark_node;
14516 		      break;
14517 		    }
14518 		  else
14519 		    {
14520 		      TREE_PROTECTED (elt) = TREE_PROTECTED (t);
14521 		      TREE_PRIVATE (elt) = TREE_PRIVATE (t);
14522 		    }
14523 		  TREE_VEC_ELT (r, i) = elt;
14524 		}
14525 	    }
14526 	  else
14527 	    {
14528 	      tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
14529 					     complain, in_decl);
14530 	      r = do_class_using_decl (inst_scope, name);
14531 	      if (!r)
14532 		r = error_mark_node;
14533 	      else
14534 		{
14535 		  TREE_PROTECTED (r) = TREE_PROTECTED (t);
14536 		  TREE_PRIVATE (r) = TREE_PRIVATE (t);
14537 		}
14538 	    }
14539 	}
14540       else
14541 	{
14542 	  r = copy_node (t);
14543 	  DECL_CHAIN (r) = NULL_TREE;
14544 	}
14545       break;
14546 
14547     case TYPE_DECL:
14548     case VAR_DECL:
14549       {
14550 	tree argvec = NULL_TREE;
14551 	tree gen_tmpl = NULL_TREE;
14552 	tree spec;
14553 	tree tmpl = NULL_TREE;
14554 	tree ctx;
14555 	tree type = NULL_TREE;
14556 	bool local_p;
14557 
14558 	if (TREE_TYPE (t) == error_mark_node)
14559 	  RETURN (error_mark_node);
14560 
14561 	if (TREE_CODE (t) == TYPE_DECL
14562 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
14563 	  {
14564 	    /* If this is the canonical decl, we don't have to
14565 	       mess with instantiations, and often we can't (for
14566 	       typename, template type parms and such).  Note that
14567 	       TYPE_NAME is not correct for the above test if
14568 	       we've copied the type for a typedef.  */
14569 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14570 	    if (type == error_mark_node)
14571 	      RETURN (error_mark_node);
14572 	    r = TYPE_NAME (type);
14573 	    break;
14574 	  }
14575 
14576 	/* Check to see if we already have the specialization we
14577 	   need.  */
14578 	spec = NULL_TREE;
14579 	if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
14580 	  {
14581 	    /* T is a static data member or namespace-scope entity.
14582 	       We have to substitute into namespace-scope variables
14583 	       (not just variable templates) because of cases like:
14584 
14585 	         template <class T> void f() { extern T t; }
14586 
14587 	       where the entity referenced is not known until
14588 	       instantiation time.  */
14589 	    local_p = false;
14590 	    ctx = DECL_CONTEXT (t);
14591 	    if (DECL_CLASS_SCOPE_P (t))
14592 	      {
14593 		ctx = tsubst_aggr_type (ctx, args,
14594 					complain,
14595 					in_decl, /*entering_scope=*/1);
14596 		/* If CTX is unchanged, then T is in fact the
14597 		   specialization we want.  That situation occurs when
14598 		   referencing a static data member within in its own
14599 		   class.  We can use pointer equality, rather than
14600 		   same_type_p, because DECL_CONTEXT is always
14601 		   canonical...  */
14602 		if (ctx == DECL_CONTEXT (t)
14603 		    /* ... unless T is a member template; in which
14604 		       case our caller can be willing to create a
14605 		       specialization of that template represented
14606 		       by T.  */
14607 		    && !(DECL_TI_TEMPLATE (t)
14608 			 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
14609 		  spec = t;
14610 	      }
14611 
14612 	    if (!spec)
14613 	      {
14614 		tmpl = DECL_TI_TEMPLATE (t);
14615 		gen_tmpl = most_general_template (tmpl);
14616 		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
14617 		if (argvec != error_mark_node)
14618 		  argvec = (coerce_innermost_template_parms
14619 			    (DECL_TEMPLATE_PARMS (gen_tmpl),
14620 			     argvec, t, complain,
14621 			     /*all*/true, /*defarg*/true));
14622 		if (argvec == error_mark_node)
14623 		  RETURN (error_mark_node);
14624 		hash = hash_tmpl_and_args (gen_tmpl, argvec);
14625 		spec = retrieve_specialization (gen_tmpl, argvec, hash);
14626 	      }
14627 	  }
14628 	else
14629 	  {
14630 	    /* A local variable.  */
14631 	    local_p = true;
14632 	    /* Subsequent calls to pushdecl will fill this in.  */
14633 	    ctx = NULL_TREE;
14634 	    /* Unless this is a reference to a static variable from an
14635 	       enclosing function, in which case we need to fill it in now.  */
14636 	    if (TREE_STATIC (t))
14637 	      {
14638 		tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
14639 		if (fn != current_function_decl)
14640 		  ctx = fn;
14641 	      }
14642 	    spec = retrieve_local_specialization (t);
14643 	  }
14644 	/* If we already have the specialization we need, there is
14645 	   nothing more to do.  */
14646 	if (spec)
14647 	  {
14648 	    r = spec;
14649 	    break;
14650 	  }
14651 
14652 	/* Create a new node for the specialization we need.  */
14653 	if (type == NULL_TREE)
14654 	  {
14655 	    if (is_typedef_decl (t))
14656 	      type = DECL_ORIGINAL_TYPE (t);
14657 	    else
14658 	      type = TREE_TYPE (t);
14659 	    if (VAR_P (t)
14660 		&& VAR_HAD_UNKNOWN_BOUND (t)
14661 		&& type != error_mark_node)
14662 	      type = strip_array_domain (type);
14663 	    tree sub_args = args;
14664 	    if (tree auto_node = type_uses_auto (type))
14665 	      {
14666 		/* Mask off any template args past the variable's context so we
14667 		   don't replace the auto with an unrelated argument.  */
14668 		int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
14669 		int extra = TMPL_ARGS_DEPTH (args) - nouter;
14670 		if (extra > 0)
14671 		  /* This should never happen with the new lambda instantiation
14672 		     model, but keep the handling just in case.  */
14673 		  gcc_assert (!CHECKING_P),
14674 		  sub_args = strip_innermost_template_args (args, extra);
14675 	      }
14676 	    type = tsubst (type, sub_args, complain, in_decl);
14677 	    /* Substituting the type might have recursively instantiated this
14678 	       same alias (c++/86171).  */
14679 	    if (gen_tmpl && DECL_ALIAS_TEMPLATE_P (gen_tmpl)
14680 		&& (spec = retrieve_specialization (gen_tmpl, argvec, hash)))
14681 	      {
14682 		r = spec;
14683 		break;
14684 	      }
14685 	  }
14686 	r = copy_decl (t);
14687 	if (VAR_P (r))
14688 	  {
14689 	    DECL_INITIALIZED_P (r) = 0;
14690 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
14691 	    if (type == error_mark_node)
14692 	      RETURN (error_mark_node);
14693 	    if (TREE_CODE (type) == FUNCTION_TYPE)
14694 	      {
14695 		/* It may seem that this case cannot occur, since:
14696 
14697 		   typedef void f();
14698 		   void g() { f x; }
14699 
14700 		   declares a function, not a variable.  However:
14701 
14702 		   typedef void f();
14703 		   template <typename T> void g() { T t; }
14704 		   template void g<f>();
14705 
14706 		   is an attempt to declare a variable with function
14707 		   type.  */
14708 		error ("variable %qD has function type",
14709 		       /* R is not yet sufficiently initialized, so we
14710 			  just use its name.  */
14711 		       DECL_NAME (r));
14712 		RETURN (error_mark_node);
14713 	      }
14714 	    type = complete_type (type);
14715 	    /* Wait until cp_finish_decl to set this again, to handle
14716 	       circular dependency (template/instantiate6.C). */
14717 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
14718 	    type = check_var_type (DECL_NAME (r), type,
14719 				   DECL_SOURCE_LOCATION (r));
14720 	    if (DECL_HAS_VALUE_EXPR_P (t))
14721 	      {
14722 		tree ve = DECL_VALUE_EXPR (t);
14723 		/* If the DECL_VALUE_EXPR is converted to the declared type,
14724 		   preserve the identity so that gimplify_type_sizes works.  */
14725 		bool nop = (TREE_CODE (ve) == NOP_EXPR);
14726 		if (nop)
14727 		  ve = TREE_OPERAND (ve, 0);
14728 		ve = tsubst_expr (ve, args, complain, in_decl,
14729 				  /*constant_expression_p=*/false);
14730 		if (REFERENCE_REF_P (ve))
14731 		  {
14732 		    gcc_assert (TYPE_REF_P (type));
14733 		    ve = TREE_OPERAND (ve, 0);
14734 		  }
14735 		if (nop)
14736 		  ve = build_nop (type, ve);
14737 		else
14738 		  gcc_checking_assert (TREE_TYPE (ve) == type);
14739 		SET_DECL_VALUE_EXPR (r, ve);
14740 	      }
14741 	    if (CP_DECL_THREAD_LOCAL_P (r)
14742 		&& !processing_template_decl)
14743 	      set_decl_tls_model (r, decl_default_tls_model (r));
14744 	  }
14745 	else if (DECL_SELF_REFERENCE_P (t))
14746 	  SET_DECL_SELF_REFERENCE_P (r);
14747 	TREE_TYPE (r) = type;
14748 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
14749 	DECL_CONTEXT (r) = ctx;
14750 	/* Clear out the mangled name and RTL for the instantiation.  */
14751 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
14752 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
14753 	  SET_DECL_RTL (r, NULL);
14754 	/* The initializer must not be expanded until it is required;
14755 	   see [temp.inst].  */
14756 	DECL_INITIAL (r) = NULL_TREE;
14757 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
14758 	if (VAR_P (r))
14759 	  {
14760 	    if (DECL_LANG_SPECIFIC (r))
14761 	      SET_DECL_DEPENDENT_INIT_P (r, false);
14762 
14763 	    SET_DECL_MODE (r, VOIDmode);
14764 
14765 	    /* Possibly limit visibility based on template args.  */
14766 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
14767 	    if (DECL_VISIBILITY_SPECIFIED (t))
14768 	      {
14769 		DECL_VISIBILITY_SPECIFIED (r) = 0;
14770 		DECL_ATTRIBUTES (r)
14771 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
14772 	      }
14773 	    determine_visibility (r);
14774 	  }
14775 
14776 	if (!local_p)
14777 	  {
14778 	    /* A static data member declaration is always marked
14779 	       external when it is declared in-class, even if an
14780 	       initializer is present.  We mimic the non-template
14781 	       processing here.  */
14782 	    DECL_EXTERNAL (r) = 1;
14783 	    if (DECL_NAMESPACE_SCOPE_P (t))
14784 	      DECL_NOT_REALLY_EXTERN (r) = 1;
14785 
14786 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
14787 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
14788 	    /* Remember whether we require constant initialization of
14789 	       a non-constant template variable.  */
14790 	    TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (r))
14791 	      = TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (t));
14792 	    if (!error_operand_p (r) || (complain & tf_error))
14793 	      register_specialization (r, gen_tmpl, argvec, false, hash);
14794 	  }
14795 	else
14796 	  {
14797 	    if (DECL_LANG_SPECIFIC (r))
14798 	      DECL_TEMPLATE_INFO (r) = NULL_TREE;
14799 	    if (!cp_unevaluated_operand)
14800 	      register_local_specialization (r, t);
14801 	  }
14802 
14803 	DECL_CHAIN (r) = NULL_TREE;
14804 
14805 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
14806 					/*flags=*/0,
14807 					args, complain, in_decl);
14808 
14809 	/* Preserve a typedef that names a type.  */
14810 	if (is_typedef_decl (r) && type != error_mark_node)
14811 	  {
14812 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
14813 	    set_underlying_type (r);
14814 	    if (TYPE_DECL_ALIAS_P (r))
14815 	      /* An alias template specialization can be dependent
14816 		 even if its underlying type is not.  */
14817 	      TYPE_DEPENDENT_P_VALID (TREE_TYPE (r)) = false;
14818 	  }
14819 
14820 	layout_decl (r, 0);
14821       }
14822       break;
14823 
14824     default:
14825       gcc_unreachable ();
14826     }
14827 #undef RETURN
14828 
14829  out:
14830   /* Restore the file and line information.  */
14831   input_location = saved_loc;
14832 
14833   return r;
14834 }
14835 
14836 /* Substitute into the complete parameter type list PARMS.  */
14837 
14838 tree
tsubst_function_parms(tree parms,tree args,tsubst_flags_t complain,tree in_decl)14839 tsubst_function_parms (tree parms,
14840 		       tree args,
14841 		       tsubst_flags_t complain,
14842 		       tree in_decl)
14843 {
14844   return tsubst_arg_types (parms, args, NULL_TREE, complain, in_decl);
14845 }
14846 
14847 /* Substitute into the ARG_TYPES of a function type.
14848    If END is a TREE_CHAIN, leave it and any following types
14849    un-substituted.  */
14850 
14851 static tree
tsubst_arg_types(tree arg_types,tree args,tree end,tsubst_flags_t complain,tree in_decl)14852 tsubst_arg_types (tree arg_types,
14853 		  tree args,
14854 		  tree end,
14855 		  tsubst_flags_t complain,
14856 		  tree in_decl)
14857 {
14858   tree remaining_arg_types;
14859   tree type = NULL_TREE;
14860   int i = 1;
14861   tree expanded_args = NULL_TREE;
14862   tree default_arg;
14863 
14864   if (!arg_types || arg_types == void_list_node || arg_types == end)
14865     return arg_types;
14866 
14867   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
14868 					  args, end, complain, in_decl);
14869   if (remaining_arg_types == error_mark_node)
14870     return error_mark_node;
14871 
14872   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
14873     {
14874       /* For a pack expansion, perform substitution on the
14875          entire expression. Later on, we'll handle the arguments
14876          one-by-one.  */
14877       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
14878                                             args, complain, in_decl);
14879 
14880       if (TREE_CODE (expanded_args) == TREE_VEC)
14881         /* So that we'll spin through the parameters, one by one.  */
14882         i = TREE_VEC_LENGTH (expanded_args);
14883       else
14884         {
14885           /* We only partially substituted into the parameter
14886              pack. Our type is TYPE_PACK_EXPANSION.  */
14887           type = expanded_args;
14888           expanded_args = NULL_TREE;
14889         }
14890     }
14891 
14892   while (i > 0) {
14893     --i;
14894 
14895     if (expanded_args)
14896       type = TREE_VEC_ELT (expanded_args, i);
14897     else if (!type)
14898       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
14899 
14900     if (type == error_mark_node)
14901       return error_mark_node;
14902     if (VOID_TYPE_P (type))
14903       {
14904         if (complain & tf_error)
14905           {
14906             error ("invalid parameter type %qT", type);
14907             if (in_decl)
14908               error ("in declaration %q+D", in_decl);
14909           }
14910         return error_mark_node;
14911     }
14912     /* DR 657. */
14913     if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
14914       return error_mark_node;
14915 
14916     /* Do array-to-pointer, function-to-pointer conversion, and ignore
14917        top-level qualifiers as required.  */
14918     type = cv_unqualified (type_decays_to (type));
14919 
14920     /* We do not substitute into default arguments here.  The standard
14921        mandates that they be instantiated only when needed, which is
14922        done in build_over_call.  */
14923     default_arg = TREE_PURPOSE (arg_types);
14924 
14925     /* Except that we do substitute default arguments under tsubst_lambda_expr,
14926        since the new op() won't have any associated template arguments for us
14927        to refer to later.  */
14928     if (lambda_fn_in_template_p (in_decl))
14929       default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
14930 					   false/*fn*/, false/*constexpr*/);
14931 
14932     if (default_arg && TREE_CODE (default_arg) == DEFERRED_PARSE)
14933       {
14934         /* We've instantiated a template before its default arguments
14935            have been parsed.  This can happen for a nested template
14936            class, and is not an error unless we require the default
14937            argument in a call of this function.  */
14938         remaining_arg_types =
14939           tree_cons (default_arg, type, remaining_arg_types);
14940 	vec_safe_push (DEFPARSE_INSTANTIATIONS (default_arg),
14941 		       remaining_arg_types);
14942       }
14943     else
14944       remaining_arg_types =
14945         hash_tree_cons (default_arg, type, remaining_arg_types);
14946   }
14947 
14948   return remaining_arg_types;
14949 }
14950 
14951 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
14952    *not* handle the exception-specification for FNTYPE, because the
14953    initial substitution of explicitly provided template parameters
14954    during argument deduction forbids substitution into the
14955    exception-specification:
14956 
14957      [temp.deduct]
14958 
14959      All references in the function type of the function template to  the
14960      corresponding template parameters are replaced by the specified tem-
14961      plate argument values.  If a substitution in a template parameter or
14962      in  the function type of the function template results in an invalid
14963      type, type deduction fails.  [Note: The equivalent  substitution  in
14964      exception specifications is done only when the function is instanti-
14965      ated, at which point a program is  ill-formed  if  the  substitution
14966      results in an invalid type.]  */
14967 
14968 static tree
tsubst_function_type(tree t,tree args,tsubst_flags_t complain,tree in_decl)14969 tsubst_function_type (tree t,
14970 		      tree args,
14971 		      tsubst_flags_t complain,
14972 		      tree in_decl)
14973 {
14974   tree return_type;
14975   tree arg_types = NULL_TREE;
14976 
14977   /* The TYPE_CONTEXT is not used for function/method types.  */
14978   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
14979 
14980   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
14981      failure.  */
14982   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
14983 
14984   if (late_return_type_p)
14985     {
14986       /* Substitute the argument types.  */
14987       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14988 				    complain, in_decl);
14989       if (arg_types == error_mark_node)
14990 	return error_mark_node;
14991 
14992       tree save_ccp = current_class_ptr;
14993       tree save_ccr = current_class_ref;
14994       tree this_type = (TREE_CODE (t) == METHOD_TYPE
14995 			? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
14996       bool do_inject = this_type && CLASS_TYPE_P (this_type);
14997       if (do_inject)
14998 	{
14999 	  /* DR 1207: 'this' is in scope in the trailing return type.  */
15000 	  inject_this_parameter (this_type, cp_type_quals (this_type));
15001 	}
15002 
15003       /* Substitute the return type.  */
15004       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15005 
15006       if (do_inject)
15007 	{
15008 	  current_class_ptr = save_ccp;
15009 	  current_class_ref = save_ccr;
15010 	}
15011     }
15012   else
15013     /* Substitute the return type.  */
15014     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15015 
15016   if (return_type == error_mark_node)
15017     return error_mark_node;
15018   /* DR 486 clarifies that creation of a function type with an
15019      invalid return type is a deduction failure.  */
15020   if (TREE_CODE (return_type) == ARRAY_TYPE
15021       || TREE_CODE (return_type) == FUNCTION_TYPE)
15022     {
15023       if (complain & tf_error)
15024 	{
15025 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
15026 	    error ("function returning an array");
15027 	  else
15028 	    error ("function returning a function");
15029 	}
15030       return error_mark_node;
15031     }
15032   /* And DR 657. */
15033   if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
15034     return error_mark_node;
15035 
15036   if (!late_return_type_p)
15037     {
15038       /* Substitute the argument types.  */
15039       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
15040 				    complain, in_decl);
15041       if (arg_types == error_mark_node)
15042 	return error_mark_node;
15043     }
15044 
15045   /* Construct a new type node and return it.  */
15046   return rebuild_function_or_method_type (t, return_type, arg_types,
15047 					  /*raises=*/NULL_TREE, complain);
15048 }
15049 
15050 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
15051    ARGS into that specification, and return the substituted
15052    specification.  If there is no specification, return NULL_TREE.  */
15053 
15054 static tree
tsubst_exception_specification(tree fntype,tree args,tsubst_flags_t complain,tree in_decl,bool defer_ok)15055 tsubst_exception_specification (tree fntype,
15056 				tree args,
15057 				tsubst_flags_t complain,
15058 				tree in_decl,
15059 				bool defer_ok)
15060 {
15061   tree specs;
15062   tree new_specs;
15063 
15064   specs = TYPE_RAISES_EXCEPTIONS (fntype);
15065   new_specs = NULL_TREE;
15066   if (specs && TREE_PURPOSE (specs))
15067     {
15068       /* A noexcept-specifier.  */
15069       tree expr = TREE_PURPOSE (specs);
15070       if (TREE_CODE (expr) == INTEGER_CST)
15071 	new_specs = expr;
15072       else if (defer_ok)
15073 	{
15074 	  /* Defer instantiation of noexcept-specifiers to avoid
15075 	     excessive instantiations (c++/49107).  */
15076 	  new_specs = make_node (DEFERRED_NOEXCEPT);
15077 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15078 	    {
15079 	      /* We already partially instantiated this member template,
15080 		 so combine the new args with the old.  */
15081 	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
15082 		= DEFERRED_NOEXCEPT_PATTERN (expr);
15083 	      DEFERRED_NOEXCEPT_ARGS (new_specs)
15084 		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
15085 	    }
15086 	  else
15087 	    {
15088 	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
15089 	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
15090 	    }
15091 	}
15092       else
15093 	{
15094 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
15095 	    {
15096 	      args = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr),
15097 					   args);
15098 	      expr = DEFERRED_NOEXCEPT_PATTERN (expr);
15099 	    }
15100 	  new_specs = tsubst_copy_and_build
15101 	    (expr, args, complain, in_decl, /*function_p=*/false,
15102 	     /*integral_constant_expression_p=*/true);
15103 	}
15104       new_specs = build_noexcept_spec (new_specs, complain);
15105     }
15106   else if (specs)
15107     {
15108       if (! TREE_VALUE (specs))
15109 	new_specs = specs;
15110       else
15111 	while (specs)
15112 	  {
15113 	    tree spec;
15114             int i, len = 1;
15115             tree expanded_specs = NULL_TREE;
15116 
15117             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
15118               {
15119                 /* Expand the pack expansion type.  */
15120                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
15121                                                        args, complain,
15122                                                        in_decl);
15123 
15124 		if (expanded_specs == error_mark_node)
15125 		  return error_mark_node;
15126 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
15127 		  len = TREE_VEC_LENGTH (expanded_specs);
15128 		else
15129 		  {
15130 		    /* We're substituting into a member template, so
15131 		       we got a TYPE_PACK_EXPANSION back.  Add that
15132 		       expansion and move on.  */
15133 		    gcc_assert (TREE_CODE (expanded_specs)
15134 				== TYPE_PACK_EXPANSION);
15135 		    new_specs = add_exception_specifier (new_specs,
15136 							 expanded_specs,
15137 							 complain);
15138 		    specs = TREE_CHAIN (specs);
15139 		    continue;
15140 		  }
15141               }
15142 
15143             for (i = 0; i < len; ++i)
15144               {
15145                 if (expanded_specs)
15146                   spec = TREE_VEC_ELT (expanded_specs, i);
15147                 else
15148                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
15149                 if (spec == error_mark_node)
15150                   return spec;
15151                 new_specs = add_exception_specifier (new_specs, spec,
15152                                                      complain);
15153               }
15154 
15155             specs = TREE_CHAIN (specs);
15156 	  }
15157     }
15158   return new_specs;
15159 }
15160 
15161 /* Take the tree structure T and replace template parameters used
15162    therein with the argument vector ARGS.  IN_DECL is an associated
15163    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
15164    Issue error and warning messages under control of COMPLAIN.  Note
15165    that we must be relatively non-tolerant of extensions here, in
15166    order to preserve conformance; if we allow substitutions that
15167    should not be allowed, we may allow argument deductions that should
15168    not succeed, and therefore report ambiguous overload situations
15169    where there are none.  In theory, we could allow the substitution,
15170    but indicate that it should have failed, and allow our caller to
15171    make sure that the right thing happens, but we don't try to do this
15172    yet.
15173 
15174    This function is used for dealing with types, decls and the like;
15175    for expressions, use tsubst_expr or tsubst_copy.  */
15176 
15177 tree
tsubst(tree t,tree args,tsubst_flags_t complain,tree in_decl)15178 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15179 {
15180   enum tree_code code;
15181   tree type, r = NULL_TREE;
15182 
15183   if (t == NULL_TREE || t == error_mark_node
15184       || t == integer_type_node
15185       || t == void_type_node
15186       || t == char_type_node
15187       || t == unknown_type_node
15188       || TREE_CODE (t) == NAMESPACE_DECL
15189       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
15190     return t;
15191 
15192   if (DECL_P (t))
15193     return tsubst_decl (t, args, complain);
15194 
15195   if (args == NULL_TREE)
15196     return t;
15197 
15198   code = TREE_CODE (t);
15199 
15200   if (code == IDENTIFIER_NODE)
15201     type = IDENTIFIER_TYPE_VALUE (t);
15202   else
15203     type = TREE_TYPE (t);
15204 
15205   gcc_assert (type != unknown_type_node);
15206 
15207   /* Reuse typedefs.  We need to do this to handle dependent attributes,
15208      such as attribute aligned.  */
15209   if (TYPE_P (t)
15210       && typedef_variant_p (t))
15211     {
15212       tree decl = TYPE_NAME (t);
15213 
15214       if (alias_template_specialization_p (t, nt_opaque))
15215 	{
15216 	  /* DECL represents an alias template and we want to
15217 	     instantiate it.  */
15218 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15219 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15220 	  r = instantiate_alias_template (tmpl, gen_args, complain);
15221 	}
15222       else if (DECL_CLASS_SCOPE_P (decl)
15223 	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
15224 	       && uses_template_parms (DECL_CONTEXT (decl)))
15225 	{
15226 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15227 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
15228 	  r = retrieve_specialization (tmpl, gen_args, 0);
15229 	}
15230       else if (DECL_FUNCTION_SCOPE_P (decl)
15231 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
15232 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
15233 	r = retrieve_local_specialization (decl);
15234       else
15235 	/* The typedef is from a non-template context.  */
15236 	return t;
15237 
15238       if (r)
15239 	{
15240 	  r = TREE_TYPE (r);
15241 	  r = cp_build_qualified_type_real
15242 	    (r, cp_type_quals (t) | cp_type_quals (r),
15243 	     complain | tf_ignore_bad_quals);
15244 	  return r;
15245 	}
15246       else
15247 	{
15248 	  /* We don't have an instantiation yet, so drop the typedef.  */
15249 	  int quals = cp_type_quals (t);
15250 	  t = DECL_ORIGINAL_TYPE (decl);
15251 	  t = cp_build_qualified_type_real (t, quals,
15252 					    complain | tf_ignore_bad_quals);
15253 	}
15254     }
15255 
15256   bool fndecl_type = (complain & tf_fndecl_type);
15257   complain &= ~tf_fndecl_type;
15258 
15259   if (type
15260       && code != TYPENAME_TYPE
15261       && code != TEMPLATE_TYPE_PARM
15262       && code != TEMPLATE_PARM_INDEX
15263       && code != IDENTIFIER_NODE
15264       && code != FUNCTION_TYPE
15265       && code != METHOD_TYPE)
15266     type = tsubst (type, args, complain, in_decl);
15267   if (type == error_mark_node)
15268     return error_mark_node;
15269 
15270   switch (code)
15271     {
15272     case RECORD_TYPE:
15273     case UNION_TYPE:
15274     case ENUMERAL_TYPE:
15275       return tsubst_aggr_type (t, args, complain, in_decl,
15276 			       /*entering_scope=*/0);
15277 
15278     case ERROR_MARK:
15279     case IDENTIFIER_NODE:
15280     case VOID_TYPE:
15281     case REAL_TYPE:
15282     case COMPLEX_TYPE:
15283     case VECTOR_TYPE:
15284     case BOOLEAN_TYPE:
15285     case NULLPTR_TYPE:
15286     case LANG_TYPE:
15287       return t;
15288 
15289     case INTEGER_TYPE:
15290       if (t == integer_type_node)
15291 	return t;
15292 
15293       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
15294           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
15295         return t;
15296 
15297       {
15298 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
15299 
15300 	max = tsubst_expr (omax, args, complain, in_decl,
15301 			   /*integral_constant_expression_p=*/false);
15302 
15303 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
15304 	   needed.  */
15305 	if (TREE_CODE (max) == NOP_EXPR
15306 	    && TREE_SIDE_EFFECTS (omax)
15307 	    && !TREE_TYPE (max))
15308 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
15309 
15310 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
15311 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
15312 	   constant expression.  */
15313 	if (processing_template_decl
15314 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
15315 	  {
15316 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
15317 	    TREE_SIDE_EFFECTS (max) = 1;
15318 	  }
15319 
15320 	return compute_array_index_type (NULL_TREE, max, complain);
15321       }
15322 
15323     case TEMPLATE_TYPE_PARM:
15324     case TEMPLATE_TEMPLATE_PARM:
15325     case BOUND_TEMPLATE_TEMPLATE_PARM:
15326     case TEMPLATE_PARM_INDEX:
15327       {
15328 	int idx;
15329 	int level;
15330 	int levels;
15331 	tree arg = NULL_TREE;
15332 
15333 	r = NULL_TREE;
15334 
15335 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
15336 	template_parm_level_and_index (t, &level, &idx);
15337 
15338 	levels = TMPL_ARGS_DEPTH (args);
15339 	if (level <= levels
15340 	    && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
15341 	  {
15342 	    arg = TMPL_ARG (args, level, idx);
15343 
15344 	    /* See through ARGUMENT_PACK_SELECT arguments. */
15345 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
15346 	      arg = argument_pack_select_arg (arg);
15347 	  }
15348 
15349 	if (arg == error_mark_node)
15350 	  return error_mark_node;
15351 	else if (arg != NULL_TREE)
15352 	  {
15353 	    if (ARGUMENT_PACK_P (arg))
15354 	      /* If ARG is an argument pack, we don't actually want to
15355 		 perform a substitution here, because substitutions
15356 		 for argument packs are only done
15357 		 element-by-element. We can get to this point when
15358 		 substituting the type of a non-type template
15359 		 parameter pack, when that type actually contains
15360 		 template parameter packs from an outer template, e.g.,
15361 
15362 	         template<typename... Types> struct A {
15363 		   template<Types... Values> struct B { };
15364                  };  */
15365 	      return t;
15366 
15367 	    if (code == TEMPLATE_TYPE_PARM)
15368 	      {
15369 		int quals;
15370 
15371 		/* When building concept checks for the purpose of
15372 		   deducing placeholders, we can end up with wildcards
15373 		   where types are expected. Adjust this to the deduced
15374 		   value.  */
15375 		if (TREE_CODE (arg) == WILDCARD_DECL)
15376 		  arg = TREE_TYPE (TREE_TYPE (arg));
15377 
15378 		gcc_assert (TYPE_P (arg));
15379 
15380 		quals = cp_type_quals (arg) | cp_type_quals (t);
15381 
15382 		return cp_build_qualified_type_real
15383 		  (arg, quals, complain | tf_ignore_bad_quals);
15384 	      }
15385 	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15386 	      {
15387 		/* We are processing a type constructed from a
15388 		   template template parameter.  */
15389 		tree argvec = tsubst (TYPE_TI_ARGS (t),
15390 				      args, complain, in_decl);
15391 		if (argvec == error_mark_node)
15392 		  return error_mark_node;
15393 
15394 		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
15395 			    || TREE_CODE (arg) == TEMPLATE_DECL
15396 			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
15397 
15398 		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
15399 		  /* Consider this code:
15400 
15401 			template <template <class> class Template>
15402 			struct Internal {
15403 			template <class Arg> using Bind = Template<Arg>;
15404 			};
15405 
15406 			template <template <class> class Template, class Arg>
15407 			using Instantiate = Template<Arg>; //#0
15408 
15409 			template <template <class> class Template,
15410                                   class Argument>
15411 			using Bind =
15412 			  Instantiate<Internal<Template>::template Bind,
15413 				      Argument>; //#1
15414 
15415 		     When #1 is parsed, the
15416 		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
15417 		     parameter `Template' in #0 matches the
15418 		     UNBOUND_CLASS_TEMPLATE representing the argument
15419 		     `Internal<Template>::template Bind'; We then want
15420 		     to assemble the type `Bind<Argument>' that can't
15421 		     be fully created right now, because
15422 		     `Internal<Template>' not being complete, the Bind
15423 		     template cannot be looked up in that context.  So
15424 		     we need to "store" `Bind<Argument>' for later
15425 		     when the context of Bind becomes complete.  Let's
15426 		     store that in a TYPENAME_TYPE.  */
15427 		  return make_typename_type (TYPE_CONTEXT (arg),
15428 					     build_nt (TEMPLATE_ID_EXPR,
15429 						       TYPE_IDENTIFIER (arg),
15430 						       argvec),
15431 					     typename_type,
15432 					     complain);
15433 
15434 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
15435 		   are resolving nested-types in the signature of a
15436 		   member function templates.  Otherwise ARG is a
15437 		   TEMPLATE_DECL and is the real template to be
15438 		   instantiated.  */
15439 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
15440 		  arg = TYPE_NAME (arg);
15441 
15442 		r = lookup_template_class (arg,
15443 					   argvec, in_decl,
15444 					   DECL_CONTEXT (arg),
15445 					    /*entering_scope=*/0,
15446 					   complain);
15447 		return cp_build_qualified_type_real
15448 		  (r, cp_type_quals (t) | cp_type_quals (r), complain);
15449 	      }
15450 	    else if (code == TEMPLATE_TEMPLATE_PARM)
15451 	      return arg;
15452 	    else
15453 	      /* TEMPLATE_PARM_INDEX.  */
15454 	      return convert_from_reference (unshare_expr (arg));
15455 	  }
15456 
15457 	if (level == 1)
15458 	  /* This can happen during the attempted tsubst'ing in
15459 	     unify.  This means that we don't yet have any information
15460 	     about the template parameter in question.  */
15461 	  return t;
15462 
15463 	/* Early in template argument deduction substitution, we don't
15464 	   want to reduce the level of 'auto', or it will be confused
15465 	   with a normal template parm in subsequent deduction.
15466 	   Similarly, don't reduce the level of template parameters to
15467 	   avoid mismatches when deducing their types.  */
15468 	if (complain & tf_partial)
15469 	  return t;
15470 
15471 	/* If we get here, we must have been looking at a parm for a
15472 	   more deeply nested template.  Make a new version of this
15473 	   template parameter, but with a lower level.  */
15474 	switch (code)
15475 	  {
15476 	  case TEMPLATE_TYPE_PARM:
15477 	  case TEMPLATE_TEMPLATE_PARM:
15478 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
15479 	    if (cp_type_quals (t))
15480 	      {
15481 		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
15482 		r = cp_build_qualified_type_real
15483 		  (r, cp_type_quals (t),
15484 		   complain | (code == TEMPLATE_TYPE_PARM
15485 			       ? tf_ignore_bad_quals : 0));
15486 	      }
15487 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
15488 		     && PLACEHOLDER_TYPE_CONSTRAINTS (t)
15489 		     && (r = (TEMPLATE_PARM_DESCENDANTS
15490 			      (TEMPLATE_TYPE_PARM_INDEX (t))))
15491 		     && (r = TREE_TYPE (r))
15492 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (r))
15493 	      /* Break infinite recursion when substituting the constraints
15494 		 of a constrained placeholder.  */;
15495 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
15496 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (t)
15497 		     && !CLASS_PLACEHOLDER_TEMPLATE (t)
15498 		     && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
15499 			 r = TEMPLATE_PARM_DESCENDANTS (arg))
15500 		     && (TEMPLATE_PARM_LEVEL (r)
15501 			 == TEMPLATE_PARM_LEVEL (arg) - levels))
15502 		/* Cache the simple case of lowering a type parameter.  */
15503 	      r = TREE_TYPE (r);
15504 	    else
15505 	      {
15506 		r = copy_type (t);
15507 		TEMPLATE_TYPE_PARM_INDEX (r)
15508 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
15509 						r, levels, args, complain);
15510 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
15511 		TYPE_MAIN_VARIANT (r) = r;
15512 		TYPE_POINTER_TO (r) = NULL_TREE;
15513 		TYPE_REFERENCE_TO (r) = NULL_TREE;
15514 
15515                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
15516 		  {
15517 		    /* Propagate constraints on placeholders since they are
15518 		       only instantiated during satisfaction.  */
15519 		    if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
15520 		      PLACEHOLDER_TYPE_CONSTRAINTS (r) = constr;
15521 		    else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
15522 		      {
15523 			pl = tsubst_copy (pl, args, complain, in_decl);
15524 			if (TREE_CODE (pl) == TEMPLATE_TEMPLATE_PARM)
15525 			  pl = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (pl);
15526 			CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
15527 		      }
15528 		  }
15529 
15530 		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
15531 		  /* We have reduced the level of the template
15532 		     template parameter, but not the levels of its
15533 		     template parameters, so canonical_type_parameter
15534 		     will not be able to find the canonical template
15535 		     template parameter for this level. Thus, we
15536 		     require structural equality checking to compare
15537 		     TEMPLATE_TEMPLATE_PARMs. */
15538 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
15539 		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
15540 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
15541 		else
15542 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
15543 
15544 		if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
15545 		  {
15546 		    tree tinfo = TYPE_TEMPLATE_INFO (t);
15547 		    /* We might need to substitute into the types of non-type
15548 		       template parameters.  */
15549 		    tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
15550 					complain, in_decl);
15551 		    if (tmpl == error_mark_node)
15552 		      return error_mark_node;
15553 		    tree argvec = tsubst (TI_ARGS (tinfo), args,
15554 					  complain, in_decl);
15555 		    if (argvec == error_mark_node)
15556 		      return error_mark_node;
15557 
15558 		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
15559 		      = build_template_info (tmpl, argvec);
15560 		  }
15561 	      }
15562 	    break;
15563 
15564 	  case TEMPLATE_PARM_INDEX:
15565 	    /* OK, now substitute the type of the non-type parameter.  We
15566 	       couldn't do it earlier because it might be an auto parameter,
15567 	       and we wouldn't need to if we had an argument.  */
15568 	    type = tsubst (type, args, complain, in_decl);
15569 	    if (type == error_mark_node)
15570 	      return error_mark_node;
15571 	    r = reduce_template_parm_level (t, type, levels, args, complain);
15572 	    break;
15573 
15574 	  default:
15575 	    gcc_unreachable ();
15576 	  }
15577 
15578 	return r;
15579       }
15580 
15581     case TREE_LIST:
15582       {
15583 	tree purpose, value, chain;
15584 
15585 	if (t == void_list_node)
15586 	  return t;
15587 
15588 	if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
15589 	    || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
15590 	  {
15591 	    /* We have pack expansions, so expand those and
15592 	       create a new list out of it.  */
15593 
15594 	    /* Expand the argument expressions.  */
15595 	    tree purposevec = NULL_TREE;
15596 	    if (TREE_PURPOSE (t))
15597 	      purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
15598 						  complain, in_decl);
15599 	    if (purposevec == error_mark_node)
15600 	      return error_mark_node;
15601 
15602 	    tree valuevec = NULL_TREE;
15603 	    if (TREE_VALUE (t))
15604 	      valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
15605 						complain, in_decl);
15606 	    if (valuevec == error_mark_node)
15607 	      return error_mark_node;
15608 
15609 	    /* Build the rest of the list.  */
15610 	    tree chain = TREE_CHAIN (t);
15611 	    if (chain && chain != void_type_node)
15612 	      chain = tsubst (chain, args, complain, in_decl);
15613 	    if (chain == error_mark_node)
15614 	      return error_mark_node;
15615 
15616 	    /* Determine the number of arguments.  */
15617 	    int len = -1;
15618 	    if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
15619 	      {
15620 		len = TREE_VEC_LENGTH (purposevec);
15621 		gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
15622 	      }
15623 	    else if (TREE_CODE (valuevec) == TREE_VEC)
15624 	      len = TREE_VEC_LENGTH (valuevec);
15625 	    else
15626 	      {
15627 		/* Since we only performed a partial substitution into
15628 		   the argument pack, we only RETURN (a single list
15629 		   node.  */
15630 		if (purposevec == TREE_PURPOSE (t)
15631 		    && valuevec == TREE_VALUE (t)
15632 		    && chain == TREE_CHAIN (t))
15633 		  return t;
15634 
15635 		return tree_cons (purposevec, valuevec, chain);
15636 	      }
15637 
15638 	    /* Convert the argument vectors into a TREE_LIST.  */
15639 	    for (int i = len; i-- > 0; )
15640 	      {
15641 		purpose = (purposevec ? TREE_VEC_ELT (purposevec, i)
15642 			   : NULL_TREE);
15643 		value = (valuevec ? TREE_VEC_ELT (valuevec, i)
15644 			 : NULL_TREE);
15645 
15646 		/* Build the list (backwards).  */
15647 		chain = hash_tree_cons (purpose, value, chain);
15648 	      }
15649 
15650 	    return chain;
15651 	  }
15652 
15653 	purpose = TREE_PURPOSE (t);
15654 	if (purpose)
15655 	  {
15656 	    purpose = tsubst (purpose, args, complain, in_decl);
15657 	    if (purpose == error_mark_node)
15658 	      return error_mark_node;
15659 	  }
15660 	value = TREE_VALUE (t);
15661 	if (value)
15662 	  {
15663 	    value = tsubst (value, args, complain, in_decl);
15664 	    if (value == error_mark_node)
15665 	      return error_mark_node;
15666 	  }
15667 	chain = TREE_CHAIN (t);
15668 	if (chain && chain != void_type_node)
15669 	  {
15670 	    chain = tsubst (chain, args, complain, in_decl);
15671 	    if (chain == error_mark_node)
15672 	      return error_mark_node;
15673 	  }
15674 	if (purpose == TREE_PURPOSE (t)
15675 	    && value == TREE_VALUE (t)
15676 	    && chain == TREE_CHAIN (t))
15677 	  return t;
15678 	return hash_tree_cons (purpose, value, chain);
15679       }
15680 
15681     case TREE_BINFO:
15682       /* We should never be tsubsting a binfo.  */
15683       gcc_unreachable ();
15684 
15685     case TREE_VEC:
15686       /* A vector of template arguments.  */
15687       gcc_assert (!type);
15688       return tsubst_template_args (t, args, complain, in_decl);
15689 
15690     case POINTER_TYPE:
15691     case REFERENCE_TYPE:
15692       {
15693 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
15694 	  return t;
15695 
15696 	/* [temp.deduct]
15697 
15698 	   Type deduction may fail for any of the following
15699 	   reasons:
15700 
15701 	   -- Attempting to create a pointer to reference type.
15702 	   -- Attempting to create a reference to a reference type or
15703 	      a reference to void.
15704 
15705 	  Core issue 106 says that creating a reference to a reference
15706 	  during instantiation is no longer a cause for failure. We
15707 	  only enforce this check in strict C++98 mode.  */
15708 	if ((TYPE_REF_P (type)
15709 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
15710 	    || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
15711 	  {
15712 	    static location_t last_loc;
15713 
15714 	    /* We keep track of the last time we issued this error
15715 	       message to avoid spewing a ton of messages during a
15716 	       single bad template instantiation.  */
15717 	    if (complain & tf_error
15718 		&& last_loc != input_location)
15719 	      {
15720 		if (VOID_TYPE_P (type))
15721 		  error ("forming reference to void");
15722                else if (code == POINTER_TYPE)
15723                  error ("forming pointer to reference type %qT", type);
15724                else
15725 		  error ("forming reference to reference type %qT", type);
15726 		last_loc = input_location;
15727 	      }
15728 
15729 	    return error_mark_node;
15730 	  }
15731 	else if (TREE_CODE (type) == FUNCTION_TYPE
15732 		 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
15733 		     || type_memfn_rqual (type) != REF_QUAL_NONE))
15734 	  {
15735 	    if (complain & tf_error)
15736 	      {
15737 		if (code == POINTER_TYPE)
15738 		  error ("forming pointer to qualified function type %qT",
15739 			 type);
15740 		else
15741 		  error ("forming reference to qualified function type %qT",
15742 			 type);
15743 	      }
15744 	    return error_mark_node;
15745 	  }
15746 	else if (code == POINTER_TYPE)
15747 	  {
15748 	    r = build_pointer_type (type);
15749 	    if (TREE_CODE (type) == METHOD_TYPE)
15750 	      r = build_ptrmemfunc_type (r);
15751 	  }
15752 	else if (TYPE_REF_P (type))
15753 	  /* In C++0x, during template argument substitution, when there is an
15754 	     attempt to create a reference to a reference type, reference
15755 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
15756 
15757 	     "If a template-argument for a template-parameter T names a type
15758 	     that is a reference to a type A, an attempt to create the type
15759 	     'lvalue reference to cv T' creates the type 'lvalue reference to
15760 	     A,' while an attempt to create the type type rvalue reference to
15761 	     cv T' creates the type T"
15762 	  */
15763 	  r = cp_build_reference_type
15764 	      (TREE_TYPE (type),
15765 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
15766 	else
15767 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
15768 	r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
15769 
15770 	if (r != error_mark_node)
15771 	  /* Will this ever be needed for TYPE_..._TO values?  */
15772 	  layout_type (r);
15773 
15774 	return r;
15775       }
15776     case OFFSET_TYPE:
15777       {
15778 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
15779 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
15780 	  {
15781 	    /* [temp.deduct]
15782 
15783 	       Type deduction may fail for any of the following
15784 	       reasons:
15785 
15786 	       -- Attempting to create "pointer to member of T" when T
15787 		  is not a class type.  */
15788 	    if (complain & tf_error)
15789 	      error ("creating pointer to member of non-class type %qT", r);
15790 	    return error_mark_node;
15791 	  }
15792 	if (TYPE_REF_P (type))
15793 	  {
15794 	    if (complain & tf_error)
15795 	      error ("creating pointer to member reference type %qT", type);
15796 	    return error_mark_node;
15797 	  }
15798 	if (VOID_TYPE_P (type))
15799 	  {
15800 	    if (complain & tf_error)
15801 	      error ("creating pointer to member of type void");
15802 	    return error_mark_node;
15803 	  }
15804 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
15805 	if (TREE_CODE (type) == FUNCTION_TYPE)
15806 	  {
15807 	    /* The type of the implicit object parameter gets its
15808 	       cv-qualifiers from the FUNCTION_TYPE. */
15809 	    tree memptr;
15810 	    tree method_type
15811 	      = build_memfn_type (type, r, type_memfn_quals (type),
15812 				  type_memfn_rqual (type));
15813 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
15814 	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
15815 						 complain);
15816 	  }
15817 	else
15818 	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
15819 					       cp_type_quals (t),
15820 					       complain);
15821       }
15822     case FUNCTION_TYPE:
15823     case METHOD_TYPE:
15824       {
15825 	tree fntype;
15826 	tree specs;
15827 	fntype = tsubst_function_type (t, args, complain, in_decl);
15828 	if (fntype == error_mark_node)
15829 	  return error_mark_node;
15830 
15831 	/* Substitute the exception specification.  */
15832 	specs = tsubst_exception_specification (t, args, complain, in_decl,
15833 						/*defer_ok*/fndecl_type);
15834 	if (specs == error_mark_node)
15835 	  return error_mark_node;
15836 	if (specs)
15837 	  fntype = build_exception_variant (fntype, specs);
15838 	return fntype;
15839       }
15840     case ARRAY_TYPE:
15841       {
15842 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
15843 	if (domain == error_mark_node)
15844 	  return error_mark_node;
15845 
15846 	/* As an optimization, we avoid regenerating the array type if
15847 	   it will obviously be the same as T.  */
15848 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
15849 	  return t;
15850 
15851 	/* These checks should match the ones in create_array_type_for_decl.
15852 
15853 	   [temp.deduct]
15854 
15855 	   The deduction may fail for any of the following reasons:
15856 
15857 	   -- Attempting to create an array with an element type that
15858 	      is void, a function type, or a reference type, or [DR337]
15859 	      an abstract class type.  */
15860 	if (VOID_TYPE_P (type)
15861 	    || TREE_CODE (type) == FUNCTION_TYPE
15862 	    || (TREE_CODE (type) == ARRAY_TYPE
15863 		&& TYPE_DOMAIN (type) == NULL_TREE)
15864 	    || TYPE_REF_P (type))
15865 	  {
15866 	    if (complain & tf_error)
15867 	      error ("creating array of %qT", type);
15868 	    return error_mark_node;
15869 	  }
15870 
15871 	if (!verify_type_context (input_location, TCTX_ARRAY_ELEMENT, type,
15872 				  !(complain & tf_error)))
15873 	  return error_mark_node;
15874 
15875 	if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
15876 	  return error_mark_node;
15877 
15878 	r = build_cplus_array_type (type, domain);
15879 
15880 	if (!valid_array_size_p (input_location, r, in_decl,
15881 				 (complain & tf_error)))
15882 	  return error_mark_node;
15883 
15884 	if (TYPE_USER_ALIGN (t))
15885 	  {
15886 	    SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
15887 	    TYPE_USER_ALIGN (r) = 1;
15888 	  }
15889 
15890 	return r;
15891       }
15892 
15893     case TYPENAME_TYPE:
15894       {
15895 	tree ctx = TYPE_CONTEXT (t);
15896 	if (TREE_CODE (ctx) == TYPE_PACK_EXPANSION)
15897 	  {
15898 	    ctx = tsubst_pack_expansion (ctx, args, complain, in_decl);
15899 	    if (ctx == error_mark_node
15900 		|| TREE_VEC_LENGTH (ctx) > 1)
15901 	      return error_mark_node;
15902 	    if (TREE_VEC_LENGTH (ctx) == 0)
15903 	      {
15904 		if (complain & tf_error)
15905 		  error ("%qD is instantiated for an empty pack",
15906 			 TYPENAME_TYPE_FULLNAME (t));
15907 		return error_mark_node;
15908 	      }
15909 	    ctx = TREE_VEC_ELT (ctx, 0);
15910 	  }
15911 	else
15912 	  ctx = tsubst_aggr_type (ctx, args, complain, in_decl,
15913 				  /*entering_scope=*/1);
15914 	if (ctx == error_mark_node)
15915 	  return error_mark_node;
15916 
15917 	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
15918 			      complain, in_decl);
15919 	if (f == error_mark_node)
15920 	  return error_mark_node;
15921 
15922 	if (!MAYBE_CLASS_TYPE_P (ctx))
15923 	  {
15924 	    if (complain & tf_error)
15925 	      error ("%qT is not a class, struct, or union type", ctx);
15926 	    return error_mark_node;
15927 	  }
15928 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
15929 	  {
15930 	    /* Normally, make_typename_type does not require that the CTX
15931 	       have complete type in order to allow things like:
15932 
15933 		 template <class T> struct S { typename S<T>::X Y; };
15934 
15935 	       But, such constructs have already been resolved by this
15936 	       point, so here CTX really should have complete type, unless
15937 	       it's a partial instantiation.  */
15938 	    ctx = complete_type (ctx);
15939 	    if (!COMPLETE_TYPE_P (ctx))
15940 	      {
15941 		if (complain & tf_error)
15942 		  cxx_incomplete_type_error (NULL_TREE, ctx);
15943 		return error_mark_node;
15944 	      }
15945 	  }
15946 
15947 	f = make_typename_type (ctx, f, typename_type,
15948 				complain | tf_keep_type_decl);
15949 	if (f == error_mark_node)
15950 	  return f;
15951 	if (TREE_CODE (f) == TYPE_DECL)
15952 	  {
15953 	    complain |= tf_ignore_bad_quals;
15954 	    f = TREE_TYPE (f);
15955 	  }
15956 
15957 	if (TREE_CODE (f) != TYPENAME_TYPE)
15958 	  {
15959 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
15960 	      {
15961 		if (complain & tf_error)
15962 		  error ("%qT resolves to %qT, which is not an enumeration type",
15963 			 t, f);
15964 		else
15965 		  return error_mark_node;
15966 	      }
15967 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
15968 	      {
15969 		if (complain & tf_error)
15970 		  error ("%qT resolves to %qT, which is not a class type",
15971 			 t, f);
15972 		else
15973 		  return error_mark_node;
15974 	      }
15975 	  }
15976 
15977 	return cp_build_qualified_type_real
15978 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
15979       }
15980 
15981     case UNBOUND_CLASS_TEMPLATE:
15982       {
15983 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
15984 				     in_decl, /*entering_scope=*/1);
15985 	tree name = TYPE_IDENTIFIER (t);
15986 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
15987 
15988 	if (ctx == error_mark_node || name == error_mark_node)
15989 	  return error_mark_node;
15990 
15991 	if (parm_list)
15992 	  parm_list = tsubst_template_parms (parm_list, args, complain);
15993 	return make_unbound_class_template (ctx, name, parm_list, complain);
15994       }
15995 
15996     case TYPEOF_TYPE:
15997       {
15998 	tree type;
15999 
16000 	++cp_unevaluated_operand;
16001 	++c_inhibit_evaluation_warnings;
16002 
16003 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
16004 			    complain, in_decl,
16005 			    /*integral_constant_expression_p=*/false);
16006 
16007 	--cp_unevaluated_operand;
16008 	--c_inhibit_evaluation_warnings;
16009 
16010 	type = finish_typeof (type);
16011 	return cp_build_qualified_type_real (type,
16012 					     cp_type_quals (t)
16013 					     | cp_type_quals (type),
16014 					     complain);
16015       }
16016 
16017     case DECLTYPE_TYPE:
16018       {
16019 	tree type;
16020 
16021 	++cp_unevaluated_operand;
16022 	++c_inhibit_evaluation_warnings;
16023 
16024 	type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
16025 				      complain|tf_decltype, in_decl,
16026 				      /*function_p*/false,
16027 				      /*integral_constant_expression*/false);
16028 
16029 	--cp_unevaluated_operand;
16030 	--c_inhibit_evaluation_warnings;
16031 
16032 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
16033 	  type = lambda_capture_field_type (type,
16034 					    false /*explicit_init*/,
16035 					    DECLTYPE_FOR_REF_CAPTURE (t));
16036 	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
16037 	  type = lambda_proxy_type (type);
16038 	else
16039 	  {
16040 	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
16041 	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
16042 		&& EXPR_P (type))
16043 	      /* In a template ~id could be either a complement expression
16044 		 or an unqualified-id naming a destructor; if instantiating
16045 		 it produces an expression, it's not an id-expression or
16046 		 member access.  */
16047 	      id = false;
16048 	    type = finish_decltype_type (type, id, complain);
16049 	  }
16050 	return cp_build_qualified_type_real (type,
16051 					     cp_type_quals (t)
16052 					     | cp_type_quals (type),
16053 					     complain | tf_ignore_bad_quals);
16054       }
16055 
16056     case UNDERLYING_TYPE:
16057       {
16058 	tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
16059 			    complain, in_decl);
16060 	return finish_underlying_type (type);
16061       }
16062 
16063     case TYPE_ARGUMENT_PACK:
16064     case NONTYPE_ARGUMENT_PACK:
16065       {
16066         tree r;
16067 
16068 	if (code == NONTYPE_ARGUMENT_PACK)
16069 	  r = make_node (code);
16070 	else
16071 	  r = cxx_make_type (code);
16072 
16073 	tree pack_args = ARGUMENT_PACK_ARGS (t);
16074 	pack_args = tsubst_template_args (pack_args, args, complain, in_decl);
16075 	SET_ARGUMENT_PACK_ARGS (r, pack_args);
16076 
16077 	return r;
16078       }
16079 
16080     case VOID_CST:
16081     case INTEGER_CST:
16082     case REAL_CST:
16083     case STRING_CST:
16084     case PLUS_EXPR:
16085     case MINUS_EXPR:
16086     case NEGATE_EXPR:
16087     case NOP_EXPR:
16088     case INDIRECT_REF:
16089     case ADDR_EXPR:
16090     case CALL_EXPR:
16091     case ARRAY_REF:
16092     case SCOPE_REF:
16093       /* We should use one of the expression tsubsts for these codes.  */
16094       gcc_unreachable ();
16095 
16096     default:
16097       sorry ("use of %qs in template", get_tree_code_name (code));
16098       return error_mark_node;
16099     }
16100 }
16101 
16102 /* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
16103    expression on the left-hand side of the "." or "->" operator.  We
16104    only do the lookup if we had a dependent BASELINK.  Otherwise we
16105    adjust it onto the instantiated heirarchy.  */
16106 
16107 static tree
tsubst_baselink(tree baselink,tree object_type,tree args,tsubst_flags_t complain,tree in_decl)16108 tsubst_baselink (tree baselink, tree object_type,
16109 		 tree args, tsubst_flags_t complain, tree in_decl)
16110 {
16111   bool qualified_p = BASELINK_QUALIFIED_P (baselink);
16112   tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
16113   qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
16114 
16115   tree optype = BASELINK_OPTYPE (baselink);
16116   optype = tsubst (optype, args, complain, in_decl);
16117 
16118   tree template_args = NULL_TREE;
16119   bool template_id_p = false;
16120   tree fns = BASELINK_FUNCTIONS (baselink);
16121   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
16122     {
16123       template_id_p = true;
16124       template_args = TREE_OPERAND (fns, 1);
16125       fns = TREE_OPERAND (fns, 0);
16126       if (template_args)
16127 	template_args = tsubst_template_args (template_args, args,
16128 					      complain, in_decl);
16129     }
16130 
16131   tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
16132   binfo_type = tsubst (binfo_type, args, complain, in_decl);
16133   bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
16134 
16135   if (dependent_p)
16136     {
16137       tree name = OVL_NAME (fns);
16138       if (IDENTIFIER_CONV_OP_P (name))
16139 	name = make_conv_op_name (optype);
16140 
16141       if (name == complete_dtor_identifier)
16142 	/* Treat as-if non-dependent below.  */
16143 	dependent_p = false;
16144 
16145       baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
16146       if (!baselink)
16147 	{
16148 	  if ((complain & tf_error)
16149 	      && constructor_name_p (name, qualifying_scope))
16150 	    error ("cannot call constructor %<%T::%D%> directly",
16151 		   qualifying_scope, name);
16152 	  return error_mark_node;
16153 	}
16154 
16155       if (BASELINK_P (baselink))
16156 	fns = BASELINK_FUNCTIONS (baselink);
16157     }
16158   else
16159     /* We're going to overwrite pieces below, make a duplicate.  */
16160     baselink = copy_node (baselink);
16161 
16162   /* If lookup found a single function, mark it as used at this point.
16163      (If lookup found multiple functions the one selected later by
16164      overload resolution will be marked as used at that point.)  */
16165   if (!template_id_p && !really_overloaded_fn (fns))
16166     {
16167       tree fn = OVL_FIRST (fns);
16168       bool ok = mark_used (fn, complain);
16169       if (!ok && !(complain & tf_error))
16170 	return error_mark_node;
16171       if (ok && BASELINK_P (baselink))
16172 	/* We might have instantiated an auto function.  */
16173 	TREE_TYPE (baselink) = TREE_TYPE (fn);
16174     }
16175 
16176   if (BASELINK_P (baselink))
16177     {
16178       /* Add back the template arguments, if present.  */
16179       if (template_id_p)
16180 	BASELINK_FUNCTIONS (baselink)
16181 	  = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
16182 
16183       /* Update the conversion operator type.  */
16184       BASELINK_OPTYPE (baselink) = optype;
16185     }
16186 
16187   if (!object_type)
16188     object_type = current_class_type;
16189 
16190   if (qualified_p || !dependent_p)
16191     {
16192       baselink = adjust_result_of_qualified_name_lookup (baselink,
16193 							 qualifying_scope,
16194 							 object_type);
16195       if (!qualified_p)
16196 	/* We need to call adjust_result_of_qualified_name_lookup in case the
16197 	   destructor names a base class, but we unset BASELINK_QUALIFIED_P
16198 	   so that we still get virtual function binding.  */
16199 	BASELINK_QUALIFIED_P (baselink) = false;
16200     }
16201 
16202   return baselink;
16203 }
16204 
16205 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
16206    true if the qualified-id will be a postfix-expression in-and-of
16207    itself; false if more of the postfix-expression follows the
16208    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
16209    of "&".  */
16210 
16211 static tree
tsubst_qualified_id(tree qualified_id,tree args,tsubst_flags_t complain,tree in_decl,bool done,bool address_p)16212 tsubst_qualified_id (tree qualified_id, tree args,
16213 		     tsubst_flags_t complain, tree in_decl,
16214 		     bool done, bool address_p)
16215 {
16216   tree expr;
16217   tree scope;
16218   tree name;
16219   bool is_template;
16220   tree template_args;
16221   location_t loc = UNKNOWN_LOCATION;
16222 
16223   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
16224 
16225   /* Figure out what name to look up.  */
16226   name = TREE_OPERAND (qualified_id, 1);
16227   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
16228     {
16229       is_template = true;
16230       loc = EXPR_LOCATION (name);
16231       template_args = TREE_OPERAND (name, 1);
16232       if (template_args)
16233 	template_args = tsubst_template_args (template_args, args,
16234 					      complain, in_decl);
16235       if (template_args == error_mark_node)
16236 	return error_mark_node;
16237       name = TREE_OPERAND (name, 0);
16238     }
16239   else
16240     {
16241       is_template = false;
16242       template_args = NULL_TREE;
16243     }
16244 
16245   /* Substitute into the qualifying scope.  When there are no ARGS, we
16246      are just trying to simplify a non-dependent expression.  In that
16247      case the qualifying scope may be dependent, and, in any case,
16248      substituting will not help.  */
16249   scope = TREE_OPERAND (qualified_id, 0);
16250   if (args)
16251     {
16252       scope = tsubst (scope, args, complain, in_decl);
16253       expr = tsubst_copy (name, args, complain, in_decl);
16254     }
16255   else
16256     expr = name;
16257 
16258   if (dependent_scope_p (scope))
16259     {
16260       if (is_template)
16261 	expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
16262       tree r = build_qualified_name (NULL_TREE, scope, expr,
16263 				     QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
16264       REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
16265       return r;
16266     }
16267 
16268   if (!BASELINK_P (name) && !DECL_P (expr))
16269     {
16270       if (TREE_CODE (expr) == BIT_NOT_EXPR)
16271 	{
16272 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
16273 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
16274 	    {
16275 	      error ("qualifying type %qT does not match destructor name ~%qT",
16276 		     scope, TREE_OPERAND (expr, 0));
16277 	      expr = error_mark_node;
16278 	    }
16279 	  else
16280 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
16281 					  /*is_type_p=*/0, false);
16282 	}
16283       else
16284 	expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
16285       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
16286 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
16287 	{
16288 	  if (complain & tf_error)
16289 	    {
16290 	      error ("dependent-name %qE is parsed as a non-type, but "
16291 		     "instantiation yields a type", qualified_id);
16292 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
16293 	    }
16294 	  return error_mark_node;
16295 	}
16296     }
16297 
16298   if (DECL_P (expr))
16299     {
16300       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
16301 					   scope);
16302       /* Remember that there was a reference to this entity.  */
16303       if (!mark_used (expr, complain) && !(complain & tf_error))
16304 	return error_mark_node;
16305     }
16306 
16307   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
16308     {
16309       if (complain & tf_error)
16310 	qualified_name_lookup_error (scope,
16311 				     TREE_OPERAND (qualified_id, 1),
16312 				     expr, input_location);
16313       return error_mark_node;
16314     }
16315 
16316   if (is_template)
16317     {
16318       /* We may be repeating a check already done during parsing, but
16319 	 if it was well-formed and passed then, it will pass again
16320 	 now, and if it didn't, we wouldn't have got here.  The case
16321 	 we want to catch is when we couldn't tell then, and can now,
16322 	 namely when templ prior to substitution was an
16323 	 identifier.  */
16324       if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
16325 	return error_mark_node;
16326 
16327       if (variable_template_p (expr))
16328 	expr = lookup_and_finish_template_variable (expr, template_args,
16329 						    complain);
16330       else
16331 	expr = lookup_template_function (expr, template_args);
16332     }
16333 
16334   if (expr == error_mark_node && complain & tf_error)
16335     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
16336 				 expr, input_location);
16337   else if (TYPE_P (scope))
16338     {
16339       expr = (adjust_result_of_qualified_name_lookup
16340 	      (expr, scope, current_nonlambda_class_type ()));
16341       expr = (finish_qualified_id_expr
16342 	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
16343 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
16344 	       /*template_arg_p=*/false, complain));
16345     }
16346 
16347   /* Expressions do not generally have reference type.  */
16348   if (TREE_CODE (expr) != SCOPE_REF
16349       /* However, if we're about to form a pointer-to-member, we just
16350 	 want the referenced member referenced.  */
16351       && TREE_CODE (expr) != OFFSET_REF)
16352     expr = convert_from_reference (expr);
16353 
16354   if (REF_PARENTHESIZED_P (qualified_id))
16355     expr = force_paren_expr (expr);
16356 
16357   return expr;
16358 }
16359 
16360 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
16361    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
16362    for tsubst.  */
16363 
16364 static tree
tsubst_init(tree init,tree decl,tree args,tsubst_flags_t complain,tree in_decl)16365 tsubst_init (tree init, tree decl, tree args,
16366 	     tsubst_flags_t complain, tree in_decl)
16367 {
16368   if (!init)
16369     return NULL_TREE;
16370 
16371   init = tsubst_expr (init, args, complain, in_decl, false);
16372 
16373   tree type = TREE_TYPE (decl);
16374 
16375   if (!init && type != error_mark_node)
16376     {
16377       if (tree auto_node = type_uses_auto (type))
16378 	{
16379 	  if (!CLASS_PLACEHOLDER_TEMPLATE (auto_node))
16380 	    {
16381 	      if (complain & tf_error)
16382 		error ("initializer for %q#D expands to an empty list "
16383 		       "of expressions", decl);
16384 	      return error_mark_node;
16385 	    }
16386 	}
16387       else if (!dependent_type_p (type))
16388 	{
16389 	  /* If we had an initializer but it
16390 	     instantiated to nothing,
16391 	     value-initialize the object.  This will
16392 	     only occur when the initializer was a
16393 	     pack expansion where the parameter packs
16394 	     used in that expansion were of length
16395 	     zero.  */
16396 	  init = build_value_init (type, complain);
16397 	  if (TREE_CODE (init) == AGGR_INIT_EXPR)
16398 	    init = get_target_expr_sfinae (init, complain);
16399 	  if (TREE_CODE (init) == TARGET_EXPR)
16400 	    TARGET_EXPR_DIRECT_INIT_P (init) = true;
16401 	}
16402     }
16403 
16404   return init;
16405 }
16406 
16407 /* If T is a reference to a dependent member of the current instantiation C and
16408    we are trying to refer to that member in a partial instantiation of C,
16409    return a SCOPE_REF; otherwise, return NULL_TREE.
16410 
16411    This can happen when forming a C++20 alias template deduction guide, as in
16412    PR96199.  */
16413 
16414 static tree
maybe_dependent_member_ref(tree t,tree args,tsubst_flags_t complain,tree in_decl)16415 maybe_dependent_member_ref (tree t, tree args, tsubst_flags_t complain,
16416 			    tree in_decl)
16417 {
16418   if (cxx_dialect < cxx2a)
16419     return NULL_TREE;
16420 
16421   tree ctx = context_for_name_lookup (t);
16422   if (!CLASS_TYPE_P (ctx))
16423     return NULL_TREE;
16424 
16425   ctx = tsubst (ctx, args, complain, in_decl);
16426   if (dependent_scope_p (ctx))
16427     return build_qualified_name (NULL_TREE, ctx, DECL_NAME (t),
16428 				 /*template_p=*/false);
16429 
16430   return NULL_TREE;
16431 }
16432 
16433 /* Like tsubst, but deals with expressions.  This function just replaces
16434    template parms; to finish processing the resultant expression, use
16435    tsubst_copy_and_build or tsubst_expr.  */
16436 
16437 static tree
tsubst_copy(tree t,tree args,tsubst_flags_t complain,tree in_decl)16438 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
16439 {
16440   enum tree_code code;
16441   tree r;
16442 
16443   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
16444     return t;
16445 
16446   code = TREE_CODE (t);
16447 
16448   switch (code)
16449     {
16450     case PARM_DECL:
16451       r = retrieve_local_specialization (t);
16452 
16453       if (r == NULL_TREE)
16454 	{
16455 	  /* We get here for a use of 'this' in an NSDMI.  */
16456 	  if (DECL_NAME (t) == this_identifier && current_class_ptr)
16457 	    return current_class_ptr;
16458 
16459 	  /* This can happen for a parameter name used later in a function
16460 	     declaration (such as in a late-specified return type).  Just
16461 	     make a dummy decl, since it's only used for its type.  */
16462 	  gcc_assert (cp_unevaluated_operand != 0);
16463 	  r = tsubst_decl (t, args, complain);
16464 	  /* Give it the template pattern as its context; its true context
16465 	     hasn't been instantiated yet and this is good enough for
16466 	     mangling.  */
16467 	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
16468 	}
16469 
16470       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
16471 	r = argument_pack_select_arg (r);
16472       if (!mark_used (r, complain) && !(complain & tf_error))
16473 	return error_mark_node;
16474       return r;
16475 
16476     case CONST_DECL:
16477       {
16478 	tree enum_type;
16479 	tree v;
16480 
16481 	if (DECL_TEMPLATE_PARM_P (t))
16482 	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
16483 	/* There is no need to substitute into namespace-scope
16484 	   enumerators.  */
16485 	if (DECL_NAMESPACE_SCOPE_P (t))
16486 	  return t;
16487 	/* If ARGS is NULL, then T is known to be non-dependent.  */
16488 	if (args == NULL_TREE)
16489 	  return scalar_constant_value (t);
16490 
16491 	if (tree ref = maybe_dependent_member_ref (t, args, complain, in_decl))
16492 	  return ref;
16493 
16494 	/* Unfortunately, we cannot just call lookup_name here.
16495 	   Consider:
16496 
16497 	     template <int I> int f() {
16498 	     enum E { a = I };
16499 	     struct S { void g() { E e = a; } };
16500 	     };
16501 
16502 	   When we instantiate f<7>::S::g(), say, lookup_name is not
16503 	   clever enough to find f<7>::a.  */
16504 	enum_type
16505 	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
16506 			      /*entering_scope=*/0);
16507 
16508 	for (v = TYPE_VALUES (enum_type);
16509 	     v != NULL_TREE;
16510 	     v = TREE_CHAIN (v))
16511 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
16512 	    return TREE_VALUE (v);
16513 
16514 	  /* We didn't find the name.  That should never happen; if
16515 	     name-lookup found it during preliminary parsing, we
16516 	     should find it again here during instantiation.  */
16517 	gcc_unreachable ();
16518       }
16519       return t;
16520 
16521     case FIELD_DECL:
16522       if (DECL_CONTEXT (t))
16523 	{
16524 	  tree ctx;
16525 
16526 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
16527 				  /*entering_scope=*/1);
16528 	  if (ctx != DECL_CONTEXT (t))
16529 	    {
16530 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
16531 	      if (!r)
16532 		{
16533 		  if (complain & tf_error)
16534 		    error ("using invalid field %qD", t);
16535 		  return error_mark_node;
16536 		}
16537 	      return r;
16538 	    }
16539 	}
16540 
16541       return t;
16542 
16543     case VAR_DECL:
16544       if (tree ref = maybe_dependent_member_ref (t, args, complain, in_decl))
16545 	return ref;
16546       gcc_fallthrough();
16547     case FUNCTION_DECL:
16548       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
16549 	r = tsubst (t, args, complain, in_decl);
16550       else if (local_variable_p (t)
16551 	       && uses_template_parms (DECL_CONTEXT (t)))
16552 	{
16553 	  r = retrieve_local_specialization (t);
16554 	  if (r == NULL_TREE)
16555 	    {
16556 	      /* First try name lookup to find the instantiation.  */
16557 	      r = lookup_name (DECL_NAME (t));
16558 	      if (r)
16559 		{
16560 		  if (!VAR_P (r))
16561 		    {
16562 		      /* During error-recovery we may find a non-variable,
16563 			 even an OVERLOAD: just bail out and avoid ICEs and
16564 			 duplicate diagnostics (c++/62207).  */
16565 		      gcc_assert (seen_error ());
16566 		      return error_mark_node;
16567 		    }
16568 		  if (!is_capture_proxy (r))
16569 		    {
16570 		      /* Make sure the one we found is the one we want.  */
16571 		      tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
16572 		      if (ctx != DECL_CONTEXT (r))
16573 			r = NULL_TREE;
16574 		    }
16575 		}
16576 
16577 	      if (r)
16578 		/* OK */;
16579 	      else
16580 		{
16581 		  /* This can happen for a variable used in a
16582 		     late-specified return type of a local lambda, or for a
16583 		     local static or constant.  Building a new VAR_DECL
16584 		     should be OK in all those cases.  */
16585 		  r = tsubst_decl (t, args, complain);
16586 		  if (local_specializations)
16587 		    /* Avoid infinite recursion (79640).  */
16588 		    register_local_specialization (r, t);
16589 		  if (decl_maybe_constant_var_p (r))
16590 		    {
16591 		      /* We can't call cp_finish_decl, so handle the
16592 			 initializer by hand.  */
16593 		      tree init = tsubst_init (DECL_INITIAL (t), r, args,
16594 					       complain, in_decl);
16595 		      if (!processing_template_decl)
16596 			init = maybe_constant_init (init);
16597 		      if (processing_template_decl
16598 			  ? potential_constant_expression (init)
16599 			  : reduced_constant_expression_p (init))
16600 			DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
16601 			  = TREE_CONSTANT (r) = true;
16602 		      DECL_INITIAL (r) = init;
16603 		      if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
16604 			TREE_TYPE (r)
16605 			  = do_auto_deduction (TREE_TYPE (r), init, auto_node,
16606 					       complain, adc_variable_type);
16607 		    }
16608 		  gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
16609 			      || decl_constant_var_p (r)
16610 			      || seen_error ());
16611 		  if (!processing_template_decl
16612 		      && !TREE_STATIC (r))
16613 		    r = process_outer_var_ref (r, complain);
16614 		}
16615 	      /* Remember this for subsequent uses.  */
16616 	      if (local_specializations)
16617 		register_local_specialization (r, t);
16618 	    }
16619 	  if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
16620 	    r = argument_pack_select_arg (r);
16621 	}
16622       else
16623 	r = t;
16624       if (!mark_used (r, complain))
16625 	return error_mark_node;
16626       return r;
16627 
16628     case NAMESPACE_DECL:
16629       return t;
16630 
16631     case OVERLOAD:
16632       return t;
16633 
16634     case BASELINK:
16635       return tsubst_baselink (t, current_nonlambda_class_type (),
16636 			      args, complain, in_decl);
16637 
16638     case TEMPLATE_DECL:
16639       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
16640 	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
16641 		       args, complain, in_decl);
16642       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
16643 	return tsubst (t, args, complain, in_decl);
16644       else if (DECL_CLASS_SCOPE_P (t)
16645 	       && uses_template_parms (DECL_CONTEXT (t)))
16646 	{
16647 	  /* Template template argument like the following example need
16648 	     special treatment:
16649 
16650 	       template <template <class> class TT> struct C {};
16651 	       template <class T> struct D {
16652 		 template <class U> struct E {};
16653 		 C<E> c;				// #1
16654 	       };
16655 	       D<int> d;				// #2
16656 
16657 	     We are processing the template argument `E' in #1 for
16658 	     the template instantiation #2.  Originally, `E' is a
16659 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
16660 	     have to substitute this with one having context `D<int>'.  */
16661 
16662 	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
16663 	  if (dependent_scope_p (context))
16664 	    {
16665 	      /* When rewriting a constructor into a deduction guide, a
16666 		 non-dependent name can become dependent, so memtmpl<args>
16667 		 becomes context::template memtmpl<args>.  */
16668 	      tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16669 	      return build_qualified_name (type, context, DECL_NAME (t),
16670 					   /*template*/true);
16671 	    }
16672 	  return lookup_field (context, DECL_NAME(t), 0, false);
16673 	}
16674       else
16675 	/* Ordinary template template argument.  */
16676 	return t;
16677 
16678     case NON_LVALUE_EXPR:
16679     case VIEW_CONVERT_EXPR:
16680 	{
16681 	  /* Handle location wrappers by substituting the wrapped node
16682 	     first, *then* reusing the resulting type.  Doing the type
16683 	     first ensures that we handle template parameters and
16684 	     parameter pack expansions.  */
16685 	  if (location_wrapper_p (t))
16686 	    {
16687 	      tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args,
16688 				      complain, in_decl);
16689 	      return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
16690 	    }
16691 	  tree op = TREE_OPERAND (t, 0);
16692 	  if (code == VIEW_CONVERT_EXPR
16693 	      && TREE_CODE (op) == TEMPLATE_PARM_INDEX)
16694 	    {
16695 	      /* Wrapper to make a C++20 template parameter object const.  */
16696 	      op = tsubst_copy (op, args, complain, in_decl);
16697 	      if (TREE_CODE (op) == TEMPLATE_PARM_INDEX)
16698 		{
16699 		  tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16700 		  return build1 (code, type, op);
16701 		}
16702 	      else if (!CP_TYPE_CONST_P (TREE_TYPE (op)))
16703 		{
16704 		  /* The template argument is not const, presumably because
16705 		     it is still dependent, and so not the const template parm
16706 		     object.  */
16707 		  tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16708 		  gcc_checking_assert (same_type_ignoring_top_level_qualifiers_p
16709 				       (type, TREE_TYPE (op)));
16710 		  if (TREE_CODE (op) == CONSTRUCTOR
16711 		      || TREE_CODE (op) == IMPLICIT_CONV_EXPR)
16712 		    {
16713 		      /* Don't add a wrapper to these.  */
16714 		      op = copy_node (op);
16715 		      TREE_TYPE (op) = type;
16716 		    }
16717 		  else
16718 		    /* Do add a wrapper otherwise.  */
16719 		    op = build1 (code, type, op);
16720 		}
16721 	      return op;
16722 	    }
16723 	  /* force_paren_expr can also create a VIEW_CONVERT_EXPR.  */
16724 	  else if (code == VIEW_CONVERT_EXPR && REF_PARENTHESIZED_P (t))
16725 	    {
16726 	      op = tsubst_copy (op, args, complain, in_decl);
16727 	      op = build1 (code, TREE_TYPE (op), op);
16728 	      REF_PARENTHESIZED_P (op) = true;
16729 	      return op;
16730 	    }
16731 	  /* We shouldn't see any other uses of these in templates.  */
16732 	  gcc_unreachable ();
16733 	}
16734 
16735     case CAST_EXPR:
16736     case REINTERPRET_CAST_EXPR:
16737     case CONST_CAST_EXPR:
16738     case STATIC_CAST_EXPR:
16739     case DYNAMIC_CAST_EXPR:
16740     case IMPLICIT_CONV_EXPR:
16741     case CONVERT_EXPR:
16742     case NOP_EXPR:
16743       {
16744 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16745 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16746 	return build1 (code, type, op0);
16747       }
16748 
16749     case SIZEOF_EXPR:
16750       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
16751 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
16752         {
16753           tree expanded, op = TREE_OPERAND (t, 0);
16754 	  int len = 0;
16755 
16756 	  if (SIZEOF_EXPR_TYPE_P (t))
16757 	    op = TREE_TYPE (op);
16758 
16759 	  ++cp_unevaluated_operand;
16760 	  ++c_inhibit_evaluation_warnings;
16761 	  /* We only want to compute the number of arguments.  */
16762 	  if (PACK_EXPANSION_P (op))
16763 	    expanded = tsubst_pack_expansion (op, args, complain, in_decl);
16764 	  else
16765 	    expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
16766 					     args, complain, in_decl);
16767 	  --cp_unevaluated_operand;
16768 	  --c_inhibit_evaluation_warnings;
16769 
16770 	  if (TREE_CODE (expanded) == TREE_VEC)
16771 	    {
16772 	      len = TREE_VEC_LENGTH (expanded);
16773 	      /* Set TREE_USED for the benefit of -Wunused.  */
16774 	      for (int i = 0; i < len; i++)
16775 		if (DECL_P (TREE_VEC_ELT (expanded, i)))
16776 		  TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
16777 	    }
16778 
16779 	  if (expanded == error_mark_node)
16780 	    return error_mark_node;
16781 	  else if (PACK_EXPANSION_P (expanded)
16782 		   || (TREE_CODE (expanded) == TREE_VEC
16783 		       && pack_expansion_args_count (expanded)))
16784 
16785 	    {
16786 	      if (PACK_EXPANSION_P (expanded))
16787 		/* OK.  */;
16788 	      else if (TREE_VEC_LENGTH (expanded) == 1)
16789 		expanded = TREE_VEC_ELT (expanded, 0);
16790 	      else
16791 		expanded = make_argument_pack (expanded);
16792 
16793 	      if (TYPE_P (expanded))
16794 		return cxx_sizeof_or_alignof_type (input_location,
16795 						   expanded, SIZEOF_EXPR,
16796 						   false,
16797 						   complain & tf_error);
16798 	      else
16799 		return cxx_sizeof_or_alignof_expr (input_location,
16800 						   expanded, SIZEOF_EXPR,
16801                                                    complain & tf_error);
16802 	    }
16803 	  else
16804 	    return build_int_cst (size_type_node, len);
16805         }
16806       if (SIZEOF_EXPR_TYPE_P (t))
16807 	{
16808 	  r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
16809 		      args, complain, in_decl);
16810 	  r = build1 (NOP_EXPR, r, error_mark_node);
16811 	  r = build1 (SIZEOF_EXPR,
16812 		      tsubst (TREE_TYPE (t), args, complain, in_decl), r);
16813 	  SIZEOF_EXPR_TYPE_P (r) = 1;
16814 	  return r;
16815 	}
16816       /* Fall through */
16817 
16818     case INDIRECT_REF:
16819     case NEGATE_EXPR:
16820     case TRUTH_NOT_EXPR:
16821     case BIT_NOT_EXPR:
16822     case ADDR_EXPR:
16823     case UNARY_PLUS_EXPR:      /* Unary + */
16824     case ALIGNOF_EXPR:
16825     case AT_ENCODE_EXPR:
16826     case ARROW_EXPR:
16827     case THROW_EXPR:
16828     case TYPEID_EXPR:
16829     case REALPART_EXPR:
16830     case IMAGPART_EXPR:
16831     case PAREN_EXPR:
16832       {
16833 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16834 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16835 	r = build1 (code, type, op0);
16836 	if (code == ALIGNOF_EXPR)
16837 	  ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
16838 	return r;
16839       }
16840 
16841     case COMPONENT_REF:
16842       {
16843 	tree object;
16844 	tree name;
16845 
16846 	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16847 	name = TREE_OPERAND (t, 1);
16848 	if (TREE_CODE (name) == BIT_NOT_EXPR)
16849 	  {
16850 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
16851 				complain, in_decl);
16852 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
16853 	  }
16854 	else if (TREE_CODE (name) == SCOPE_REF
16855 		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
16856 	  {
16857 	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
16858 				     complain, in_decl);
16859 	    name = TREE_OPERAND (name, 1);
16860 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
16861 				complain, in_decl);
16862 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
16863 	    name = build_qualified_name (/*type=*/NULL_TREE,
16864 					 base, name,
16865 					 /*template_p=*/false);
16866 	  }
16867 	else if (BASELINK_P (name))
16868 	  name = tsubst_baselink (name,
16869 				  non_reference (TREE_TYPE (object)),
16870 				  args, complain,
16871 				  in_decl);
16872 	else
16873 	  name = tsubst_copy (name, args, complain, in_decl);
16874 	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
16875       }
16876 
16877     case PLUS_EXPR:
16878     case MINUS_EXPR:
16879     case MULT_EXPR:
16880     case TRUNC_DIV_EXPR:
16881     case CEIL_DIV_EXPR:
16882     case FLOOR_DIV_EXPR:
16883     case ROUND_DIV_EXPR:
16884     case EXACT_DIV_EXPR:
16885     case BIT_AND_EXPR:
16886     case BIT_IOR_EXPR:
16887     case BIT_XOR_EXPR:
16888     case TRUNC_MOD_EXPR:
16889     case FLOOR_MOD_EXPR:
16890     case TRUTH_ANDIF_EXPR:
16891     case TRUTH_ORIF_EXPR:
16892     case TRUTH_AND_EXPR:
16893     case TRUTH_OR_EXPR:
16894     case RSHIFT_EXPR:
16895     case LSHIFT_EXPR:
16896     case EQ_EXPR:
16897     case NE_EXPR:
16898     case MAX_EXPR:
16899     case MIN_EXPR:
16900     case LE_EXPR:
16901     case GE_EXPR:
16902     case LT_EXPR:
16903     case GT_EXPR:
16904     case COMPOUND_EXPR:
16905     case DOTSTAR_EXPR:
16906     case MEMBER_REF:
16907     case PREDECREMENT_EXPR:
16908     case PREINCREMENT_EXPR:
16909     case POSTDECREMENT_EXPR:
16910     case POSTINCREMENT_EXPR:
16911       {
16912 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16913 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16914 	return build_nt (code, op0, op1);
16915       }
16916 
16917     case SCOPE_REF:
16918       {
16919 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16920 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16921 	return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
16922 				     QUALIFIED_NAME_IS_TEMPLATE (t));
16923       }
16924 
16925     case ARRAY_REF:
16926       {
16927 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16928 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16929 	return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
16930       }
16931 
16932     case CALL_EXPR:
16933       {
16934 	int n = VL_EXP_OPERAND_LENGTH (t);
16935 	tree result = build_vl_exp (CALL_EXPR, n);
16936 	int i;
16937 	for (i = 0; i < n; i++)
16938 	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
16939 					     complain, in_decl);
16940 	return result;
16941       }
16942 
16943     case COND_EXPR:
16944     case MODOP_EXPR:
16945     case PSEUDO_DTOR_EXPR:
16946     case VEC_PERM_EXPR:
16947       {
16948 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16949 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16950 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
16951 	r = build_nt (code, op0, op1, op2);
16952 	TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
16953 	return r;
16954       }
16955 
16956     case NEW_EXPR:
16957       {
16958 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16959 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16960 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
16961 	r = build_nt (code, op0, op1, op2);
16962 	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
16963 	return r;
16964       }
16965 
16966     case DELETE_EXPR:
16967       {
16968 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
16969 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
16970 	r = build_nt (code, op0, op1);
16971 	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
16972 	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
16973 	return r;
16974       }
16975 
16976     case TEMPLATE_ID_EXPR:
16977       {
16978 	/* Substituted template arguments */
16979 	tree fn = TREE_OPERAND (t, 0);
16980 	tree targs = TREE_OPERAND (t, 1);
16981 
16982 	fn = tsubst_copy (fn, args, complain, in_decl);
16983 	if (targs)
16984 	  targs = tsubst_template_args (targs, args, complain, in_decl);
16985 
16986 	return lookup_template_function (fn, targs);
16987       }
16988 
16989     case TREE_LIST:
16990       {
16991 	tree purpose, value, chain;
16992 
16993 	if (t == void_list_node)
16994 	  return t;
16995 
16996 	purpose = TREE_PURPOSE (t);
16997 	if (purpose)
16998 	  purpose = tsubst_copy (purpose, args, complain, in_decl);
16999 	value = TREE_VALUE (t);
17000 	if (value)
17001 	  value = tsubst_copy (value, args, complain, in_decl);
17002 	chain = TREE_CHAIN (t);
17003 	if (chain && chain != void_type_node)
17004 	  chain = tsubst_copy (chain, args, complain, in_decl);
17005 	if (purpose == TREE_PURPOSE (t)
17006 	    && value == TREE_VALUE (t)
17007 	    && chain == TREE_CHAIN (t))
17008 	  return t;
17009 	return tree_cons (purpose, value, chain);
17010       }
17011 
17012     case RECORD_TYPE:
17013     case UNION_TYPE:
17014     case ENUMERAL_TYPE:
17015     case INTEGER_TYPE:
17016     case TEMPLATE_TYPE_PARM:
17017     case TEMPLATE_TEMPLATE_PARM:
17018     case BOUND_TEMPLATE_TEMPLATE_PARM:
17019     case TEMPLATE_PARM_INDEX:
17020     case POINTER_TYPE:
17021     case REFERENCE_TYPE:
17022     case OFFSET_TYPE:
17023     case FUNCTION_TYPE:
17024     case METHOD_TYPE:
17025     case ARRAY_TYPE:
17026     case TYPENAME_TYPE:
17027     case UNBOUND_CLASS_TEMPLATE:
17028     case TYPEOF_TYPE:
17029     case DECLTYPE_TYPE:
17030     case TYPE_DECL:
17031       return tsubst (t, args, complain, in_decl);
17032 
17033     case USING_DECL:
17034       t = DECL_NAME (t);
17035       /* Fall through.  */
17036     case IDENTIFIER_NODE:
17037       if (IDENTIFIER_CONV_OP_P (t))
17038 	{
17039 	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17040 	  return make_conv_op_name (new_type);
17041 	}
17042       else
17043 	return t;
17044 
17045     case CONSTRUCTOR:
17046       /* This is handled by tsubst_copy_and_build.  */
17047       gcc_unreachable ();
17048 
17049     case VA_ARG_EXPR:
17050       {
17051 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17052 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17053 	return build_x_va_arg (EXPR_LOCATION (t), op0, type);
17054       }
17055 
17056     case CLEANUP_POINT_EXPR:
17057       /* We shouldn't have built any of these during initial template
17058 	 generation.  Instead, they should be built during instantiation
17059 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
17060       gcc_unreachable ();
17061 
17062     case OFFSET_REF:
17063       {
17064 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17065 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
17066 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
17067 	r = build2 (code, type, op0, op1);
17068 	PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
17069 	if (!mark_used (TREE_OPERAND (r, 1), complain)
17070 	    && !(complain & tf_error))
17071 	  return error_mark_node;
17072 	return r;
17073       }
17074 
17075     case EXPR_PACK_EXPANSION:
17076       error ("invalid use of pack expansion expression");
17077       return error_mark_node;
17078 
17079     case NONTYPE_ARGUMENT_PACK:
17080       error ("use %<...%> to expand argument pack");
17081       return error_mark_node;
17082 
17083     case VOID_CST:
17084       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
17085       return t;
17086 
17087     case INTEGER_CST:
17088     case REAL_CST:
17089     case COMPLEX_CST:
17090       {
17091 	/* Instantiate any typedefs in the type.  */
17092 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17093 	r = fold_convert (type, t);
17094 	gcc_assert (TREE_CODE (r) == code);
17095 	return r;
17096       }
17097 
17098     case STRING_CST:
17099       {
17100 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17101 	r = t;
17102 	if (type != TREE_TYPE (t))
17103 	  {
17104 	    r = copy_node (t);
17105 	    TREE_TYPE (r) = type;
17106 	  }
17107 	return r;
17108       }
17109 
17110     case PTRMEM_CST:
17111       /* These can sometimes show up in a partial instantiation, but never
17112 	 involve template parms.  */
17113       gcc_assert (!uses_template_parms (t));
17114       return t;
17115 
17116     case UNARY_LEFT_FOLD_EXPR:
17117       return tsubst_unary_left_fold (t, args, complain, in_decl);
17118     case UNARY_RIGHT_FOLD_EXPR:
17119       return tsubst_unary_right_fold (t, args, complain, in_decl);
17120     case BINARY_LEFT_FOLD_EXPR:
17121       return tsubst_binary_left_fold (t, args, complain, in_decl);
17122     case BINARY_RIGHT_FOLD_EXPR:
17123       return tsubst_binary_right_fold (t, args, complain, in_decl);
17124     case PREDICT_EXPR:
17125       return t;
17126 
17127     case DEBUG_BEGIN_STMT:
17128       /* ??? There's no point in copying it for now, but maybe some
17129 	 day it will contain more information, such as a pointer back
17130 	 to the containing function, inlined copy or so.  */
17131       return t;
17132 
17133     case CO_AWAIT_EXPR:
17134       return tsubst_expr (t, args, complain, in_decl,
17135 			  /*integral_constant_expression_p=*/false);
17136       break;
17137 
17138     default:
17139       /* We shouldn't get here, but keep going if !flag_checking.  */
17140       if (flag_checking)
17141 	gcc_unreachable ();
17142       return t;
17143     }
17144 }
17145 
17146 /* Helper function for tsubst_omp_clauses, used for instantiation of
17147    OMP_CLAUSE_DECL of clauses.  */
17148 
17149 static tree
tsubst_omp_clause_decl(tree decl,tree args,tsubst_flags_t complain,tree in_decl,tree * iterator_cache)17150 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
17151 			tree in_decl, tree *iterator_cache)
17152 {
17153   if (decl == NULL_TREE)
17154     return NULL_TREE;
17155 
17156   /* Handle OpenMP iterators.  */
17157   if (TREE_CODE (decl) == TREE_LIST
17158       && TREE_PURPOSE (decl)
17159       && TREE_CODE (TREE_PURPOSE (decl)) == TREE_VEC)
17160     {
17161       tree ret;
17162       if (iterator_cache[0] == TREE_PURPOSE (decl))
17163 	ret = iterator_cache[1];
17164       else
17165 	{
17166 	  tree *tp = &ret;
17167 	  begin_scope (sk_omp, NULL);
17168 	  for (tree it = TREE_PURPOSE (decl); it; it = TREE_CHAIN (it))
17169 	    {
17170 	      *tp = copy_node (it);
17171 	      TREE_VEC_ELT (*tp, 0)
17172 		= tsubst_decl (TREE_VEC_ELT (it, 0), args, complain);
17173 	      TREE_VEC_ELT (*tp, 1)
17174 		= tsubst_expr (TREE_VEC_ELT (it, 1), args, complain, in_decl,
17175 			       /*integral_constant_expression_p=*/false);
17176 	      TREE_VEC_ELT (*tp, 2)
17177 		= tsubst_expr (TREE_VEC_ELT (it, 2), args, complain, in_decl,
17178 			       /*integral_constant_expression_p=*/false);
17179 	      TREE_VEC_ELT (*tp, 3)
17180 		= tsubst_expr (TREE_VEC_ELT (it, 3), args, complain, in_decl,
17181 			       /*integral_constant_expression_p=*/false);
17182 	      TREE_CHAIN (*tp) = NULL_TREE;
17183 	      tp = &TREE_CHAIN (*tp);
17184 	    }
17185 	  TREE_VEC_ELT (ret, 5) = poplevel (1, 1, 0);
17186 	  iterator_cache[0] = TREE_PURPOSE (decl);
17187 	  iterator_cache[1] = ret;
17188 	}
17189       return build_tree_list (ret, tsubst_omp_clause_decl (TREE_VALUE (decl),
17190 							   args, complain,
17191 							   in_decl, NULL));
17192     }
17193 
17194   /* Handle an OpenMP array section represented as a TREE_LIST (or
17195      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
17196      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
17197      TREE_LIST.  We can handle it exactly the same as an array section
17198      (purpose, value, and a chain), even though the nomenclature
17199      (low_bound, length, etc) is different.  */
17200   if (TREE_CODE (decl) == TREE_LIST)
17201     {
17202       tree low_bound
17203 	= tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
17204 		       /*integral_constant_expression_p=*/false);
17205       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
17206 				 /*integral_constant_expression_p=*/false);
17207       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
17208 					   in_decl, NULL);
17209       if (TREE_PURPOSE (decl) == low_bound
17210 	  && TREE_VALUE (decl) == length
17211 	  && TREE_CHAIN (decl) == chain)
17212 	return decl;
17213       tree ret = tree_cons (low_bound, length, chain);
17214       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
17215 	= OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
17216       return ret;
17217     }
17218   tree ret = tsubst_expr (decl, args, complain, in_decl,
17219 			  /*integral_constant_expression_p=*/false);
17220   /* Undo convert_from_reference tsubst_expr could have called.  */
17221   if (decl
17222       && REFERENCE_REF_P (ret)
17223       && !REFERENCE_REF_P (decl))
17224     ret = TREE_OPERAND (ret, 0);
17225   return ret;
17226 }
17227 
17228 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
17229 
17230 static tree
tsubst_omp_clauses(tree clauses,enum c_omp_region_type ort,tree args,tsubst_flags_t complain,tree in_decl)17231 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
17232 		    tree args, tsubst_flags_t complain, tree in_decl)
17233 {
17234   tree new_clauses = NULL_TREE, nc, oc;
17235   tree linear_no_step = NULL_TREE;
17236   tree iterator_cache[2] = { NULL_TREE, NULL_TREE };
17237 
17238   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
17239     {
17240       nc = copy_node (oc);
17241       OMP_CLAUSE_CHAIN (nc) = new_clauses;
17242       new_clauses = nc;
17243 
17244       switch (OMP_CLAUSE_CODE (nc))
17245 	{
17246 	case OMP_CLAUSE_LASTPRIVATE:
17247 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
17248 	    {
17249 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
17250 	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
17251 			   in_decl, /*integral_constant_expression_p=*/false);
17252 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
17253 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
17254 	    }
17255 	  /* FALLTHRU */
17256 	case OMP_CLAUSE_PRIVATE:
17257 	case OMP_CLAUSE_SHARED:
17258 	case OMP_CLAUSE_FIRSTPRIVATE:
17259 	case OMP_CLAUSE_COPYIN:
17260 	case OMP_CLAUSE_COPYPRIVATE:
17261 	case OMP_CLAUSE_UNIFORM:
17262 	case OMP_CLAUSE_DEPEND:
17263 	case OMP_CLAUSE_FROM:
17264 	case OMP_CLAUSE_TO:
17265 	case OMP_CLAUSE_MAP:
17266 	case OMP_CLAUSE__CACHE_:
17267 	case OMP_CLAUSE_NONTEMPORAL:
17268 	case OMP_CLAUSE_USE_DEVICE_PTR:
17269 	case OMP_CLAUSE_USE_DEVICE_ADDR:
17270 	case OMP_CLAUSE_IS_DEVICE_PTR:
17271 	case OMP_CLAUSE_INCLUSIVE:
17272 	case OMP_CLAUSE_EXCLUSIVE:
17273 	  OMP_CLAUSE_DECL (nc)
17274 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17275 				      in_decl, iterator_cache);
17276 	  break;
17277 	case OMP_CLAUSE_TILE:
17278 	case OMP_CLAUSE_IF:
17279 	case OMP_CLAUSE_NUM_THREADS:
17280 	case OMP_CLAUSE_SCHEDULE:
17281 	case OMP_CLAUSE_COLLAPSE:
17282 	case OMP_CLAUSE_FINAL:
17283 	case OMP_CLAUSE_DEVICE:
17284 	case OMP_CLAUSE_DIST_SCHEDULE:
17285 	case OMP_CLAUSE_NUM_TEAMS:
17286 	case OMP_CLAUSE_THREAD_LIMIT:
17287 	case OMP_CLAUSE_SAFELEN:
17288 	case OMP_CLAUSE_SIMDLEN:
17289 	case OMP_CLAUSE_NUM_TASKS:
17290 	case OMP_CLAUSE_GRAINSIZE:
17291 	case OMP_CLAUSE_PRIORITY:
17292 	case OMP_CLAUSE_ORDERED:
17293 	case OMP_CLAUSE_HINT:
17294 	case OMP_CLAUSE_NUM_GANGS:
17295 	case OMP_CLAUSE_NUM_WORKERS:
17296 	case OMP_CLAUSE_VECTOR_LENGTH:
17297 	case OMP_CLAUSE_WORKER:
17298 	case OMP_CLAUSE_VECTOR:
17299 	case OMP_CLAUSE_ASYNC:
17300 	case OMP_CLAUSE_WAIT:
17301 	  OMP_CLAUSE_OPERAND (nc, 0)
17302 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
17303 			   in_decl, /*integral_constant_expression_p=*/false);
17304 	  break;
17305 	case OMP_CLAUSE_REDUCTION:
17306 	case OMP_CLAUSE_IN_REDUCTION:
17307 	case OMP_CLAUSE_TASK_REDUCTION:
17308 	  if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
17309 	    {
17310 	      tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
17311 	      if (TREE_CODE (placeholder) == SCOPE_REF)
17312 		{
17313 		  tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
17314 				       complain, in_decl);
17315 		  OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
17316 		    = build_qualified_name (NULL_TREE, scope,
17317 					    TREE_OPERAND (placeholder, 1),
17318 					    false);
17319 		}
17320 	      else
17321 		gcc_assert (identifier_p (placeholder));
17322 	    }
17323 	  OMP_CLAUSE_DECL (nc)
17324 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17325 				      in_decl, NULL);
17326 	  break;
17327 	case OMP_CLAUSE_GANG:
17328 	case OMP_CLAUSE_ALIGNED:
17329 	  OMP_CLAUSE_DECL (nc)
17330 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17331 				      in_decl, NULL);
17332 	  OMP_CLAUSE_OPERAND (nc, 1)
17333 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
17334 			   in_decl, /*integral_constant_expression_p=*/false);
17335 	  break;
17336 	case OMP_CLAUSE_LINEAR:
17337 	  OMP_CLAUSE_DECL (nc)
17338 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
17339 				      in_decl, NULL);
17340 	  if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
17341 	    {
17342 	      gcc_assert (!linear_no_step);
17343 	      linear_no_step = nc;
17344 	    }
17345 	  else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
17346 	    OMP_CLAUSE_LINEAR_STEP (nc)
17347 	      = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
17348 					complain, in_decl, NULL);
17349 	  else
17350 	    OMP_CLAUSE_LINEAR_STEP (nc)
17351 	      = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
17352 			     in_decl,
17353 			     /*integral_constant_expression_p=*/false);
17354 	  break;
17355 	case OMP_CLAUSE_NOWAIT:
17356 	case OMP_CLAUSE_DEFAULT:
17357 	case OMP_CLAUSE_UNTIED:
17358 	case OMP_CLAUSE_MERGEABLE:
17359 	case OMP_CLAUSE_INBRANCH:
17360 	case OMP_CLAUSE_NOTINBRANCH:
17361 	case OMP_CLAUSE_PROC_BIND:
17362 	case OMP_CLAUSE_FOR:
17363 	case OMP_CLAUSE_PARALLEL:
17364 	case OMP_CLAUSE_SECTIONS:
17365 	case OMP_CLAUSE_TASKGROUP:
17366 	case OMP_CLAUSE_NOGROUP:
17367 	case OMP_CLAUSE_THREADS:
17368 	case OMP_CLAUSE_SIMD:
17369 	case OMP_CLAUSE_DEFAULTMAP:
17370 	case OMP_CLAUSE_ORDER:
17371 	case OMP_CLAUSE_BIND:
17372 	case OMP_CLAUSE_INDEPENDENT:
17373 	case OMP_CLAUSE_AUTO:
17374 	case OMP_CLAUSE_SEQ:
17375 	case OMP_CLAUSE_IF_PRESENT:
17376 	case OMP_CLAUSE_FINALIZE:
17377 	  break;
17378 	default:
17379 	  gcc_unreachable ();
17380 	}
17381       if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
17382 	switch (OMP_CLAUSE_CODE (nc))
17383 	  {
17384 	  case OMP_CLAUSE_SHARED:
17385 	  case OMP_CLAUSE_PRIVATE:
17386 	  case OMP_CLAUSE_FIRSTPRIVATE:
17387 	  case OMP_CLAUSE_LASTPRIVATE:
17388 	  case OMP_CLAUSE_COPYPRIVATE:
17389 	  case OMP_CLAUSE_LINEAR:
17390 	  case OMP_CLAUSE_REDUCTION:
17391 	  case OMP_CLAUSE_IN_REDUCTION:
17392 	  case OMP_CLAUSE_TASK_REDUCTION:
17393 	  case OMP_CLAUSE_USE_DEVICE_PTR:
17394 	  case OMP_CLAUSE_USE_DEVICE_ADDR:
17395 	  case OMP_CLAUSE_IS_DEVICE_PTR:
17396 	  case OMP_CLAUSE_INCLUSIVE:
17397 	  case OMP_CLAUSE_EXCLUSIVE:
17398 	    /* tsubst_expr on SCOPE_REF results in returning
17399 	       finish_non_static_data_member result.  Undo that here.  */
17400 	    if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
17401 		&& (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
17402 		    == IDENTIFIER_NODE))
17403 	      {
17404 		tree t = OMP_CLAUSE_DECL (nc);
17405 		tree v = t;
17406 		while (v)
17407 		  switch (TREE_CODE (v))
17408 		    {
17409 		    case COMPONENT_REF:
17410 		    case MEM_REF:
17411 		    case INDIRECT_REF:
17412 		    CASE_CONVERT:
17413 		    case POINTER_PLUS_EXPR:
17414 		      v = TREE_OPERAND (v, 0);
17415 		      continue;
17416 		    case PARM_DECL:
17417 		      if (DECL_CONTEXT (v) == current_function_decl
17418 			  && DECL_ARTIFICIAL (v)
17419 			  && DECL_NAME (v) == this_identifier)
17420 			OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
17421 		      /* FALLTHRU */
17422 		    default:
17423 		      v = NULL_TREE;
17424 		      break;
17425 		    }
17426 	      }
17427 	    else if (VAR_P (OMP_CLAUSE_DECL (oc))
17428 		     && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
17429 		     && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
17430 		     && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
17431 		     && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
17432 	      {
17433 		tree decl = OMP_CLAUSE_DECL (nc);
17434 		if (VAR_P (decl))
17435 		  {
17436 		    retrofit_lang_decl (decl);
17437 		    DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
17438 		  }
17439 	      }
17440 	    break;
17441 	  default:
17442 	    break;
17443 	  }
17444     }
17445 
17446   new_clauses = nreverse (new_clauses);
17447   if (ort != C_ORT_OMP_DECLARE_SIMD)
17448     {
17449       new_clauses = finish_omp_clauses (new_clauses, ort);
17450       if (linear_no_step)
17451 	for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
17452 	  if (nc == linear_no_step)
17453 	    {
17454 	      OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
17455 	      break;
17456 	    }
17457     }
17458   return new_clauses;
17459 }
17460 
17461 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
17462 
17463 static tree
tsubst_copy_asm_operands(tree t,tree args,tsubst_flags_t complain,tree in_decl)17464 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
17465 			  tree in_decl)
17466 {
17467 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
17468 
17469   tree purpose, value, chain;
17470 
17471   if (t == NULL)
17472     return t;
17473 
17474   if (TREE_CODE (t) != TREE_LIST)
17475     return tsubst_copy_and_build (t, args, complain, in_decl,
17476 				  /*function_p=*/false,
17477 				  /*integral_constant_expression_p=*/false);
17478 
17479   if (t == void_list_node)
17480     return t;
17481 
17482   purpose = TREE_PURPOSE (t);
17483   if (purpose)
17484     purpose = RECUR (purpose);
17485   value = TREE_VALUE (t);
17486   if (value)
17487     {
17488       if (TREE_CODE (value) != LABEL_DECL)
17489 	value = RECUR (value);
17490       else
17491 	{
17492 	  value = lookup_label (DECL_NAME (value));
17493 	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
17494 	  TREE_USED (value) = 1;
17495 	}
17496     }
17497   chain = TREE_CHAIN (t);
17498   if (chain && chain != void_type_node)
17499     chain = RECUR (chain);
17500   return tree_cons (purpose, value, chain);
17501 #undef RECUR
17502 }
17503 
17504 /* Used to temporarily communicate the list of #pragma omp parallel
17505    clauses to #pragma omp for instantiation if they are combined
17506    together.  */
17507 
17508 static tree *omp_parallel_combined_clauses;
17509 
17510 static tree tsubst_decomp_names (tree, tree, tree, tsubst_flags_t, tree,
17511 				 tree *, unsigned int *);
17512 
17513 /* Substitute one OMP_FOR iterator.  */
17514 
17515 static bool
tsubst_omp_for_iterator(tree t,int i,tree declv,tree & orig_declv,tree initv,tree condv,tree incrv,tree * clauses,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)17516 tsubst_omp_for_iterator (tree t, int i, tree declv, tree &orig_declv,
17517 			 tree initv, tree condv, tree incrv, tree *clauses,
17518 			 tree args, tsubst_flags_t complain, tree in_decl,
17519 			 bool integral_constant_expression_p)
17520 {
17521 #define RECUR(NODE)				\
17522   tsubst_expr ((NODE), args, complain, in_decl,	\
17523 	       integral_constant_expression_p)
17524   tree decl, init, cond = NULL_TREE, incr = NULL_TREE;
17525   bool ret = false;
17526 
17527   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
17528   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
17529 
17530   decl = TREE_OPERAND (init, 0);
17531   init = TREE_OPERAND (init, 1);
17532   tree decl_expr = NULL_TREE;
17533   bool range_for = TREE_VEC_ELT (OMP_FOR_COND (t), i) == global_namespace;
17534   if (range_for)
17535     {
17536       bool decomp = false;
17537       if (decl != error_mark_node && DECL_HAS_VALUE_EXPR_P (decl))
17538 	{
17539 	  tree v = DECL_VALUE_EXPR (decl);
17540 	  if (TREE_CODE (v) == ARRAY_REF
17541 	      && VAR_P (TREE_OPERAND (v, 0))
17542 	      && DECL_DECOMPOSITION_P (TREE_OPERAND (v, 0)))
17543 	    {
17544 	      tree decomp_first = NULL_TREE;
17545 	      unsigned decomp_cnt = 0;
17546 	      tree d = tsubst_decl (TREE_OPERAND (v, 0), args, complain);
17547 	      maybe_push_decl (d);
17548 	      d = tsubst_decomp_names (d, TREE_OPERAND (v, 0), args, complain,
17549 				       in_decl, &decomp_first, &decomp_cnt);
17550 	      decomp = true;
17551 	      if (d == error_mark_node)
17552 		decl = error_mark_node;
17553 	      else
17554 		for (unsigned int i = 0; i < decomp_cnt; i++)
17555 		  {
17556 		    if (!DECL_HAS_VALUE_EXPR_P (decomp_first))
17557 		      {
17558 			tree v = build_nt (ARRAY_REF, d,
17559 					   size_int (decomp_cnt - i - 1),
17560 					   NULL_TREE, NULL_TREE);
17561 			SET_DECL_VALUE_EXPR (decomp_first, v);
17562 			DECL_HAS_VALUE_EXPR_P (decomp_first) = 1;
17563 		      }
17564 		    fit_decomposition_lang_decl (decomp_first, d);
17565 		    decomp_first = DECL_CHAIN (decomp_first);
17566 		  }
17567 	    }
17568 	}
17569       decl = tsubst_decl (decl, args, complain);
17570       if (!decomp)
17571 	maybe_push_decl (decl);
17572     }
17573   else if (init && TREE_CODE (init) == DECL_EXPR)
17574     {
17575       /* We need to jump through some hoops to handle declarations in the
17576 	 init-statement, since we might need to handle auto deduction,
17577 	 but we need to keep control of initialization.  */
17578       decl_expr = init;
17579       init = DECL_INITIAL (DECL_EXPR_DECL (init));
17580       decl = tsubst_decl (decl, args, complain);
17581     }
17582   else
17583     {
17584       if (TREE_CODE (decl) == SCOPE_REF)
17585 	{
17586 	  decl = RECUR (decl);
17587 	  if (TREE_CODE (decl) == COMPONENT_REF)
17588 	    {
17589 	      tree v = decl;
17590 	      while (v)
17591 		switch (TREE_CODE (v))
17592 		  {
17593 		  case COMPONENT_REF:
17594 		  case MEM_REF:
17595 		  case INDIRECT_REF:
17596 		  CASE_CONVERT:
17597 		  case POINTER_PLUS_EXPR:
17598 		    v = TREE_OPERAND (v, 0);
17599 		    continue;
17600 		  case PARM_DECL:
17601 		    if (DECL_CONTEXT (v) == current_function_decl
17602 			&& DECL_ARTIFICIAL (v)
17603 			&& DECL_NAME (v) == this_identifier)
17604 		      {
17605 			decl = TREE_OPERAND (decl, 1);
17606 			decl = omp_privatize_field (decl, false);
17607 		      }
17608 		    /* FALLTHRU */
17609 		  default:
17610 		    v = NULL_TREE;
17611 		    break;
17612 		  }
17613 	    }
17614 	}
17615       else
17616 	decl = RECUR (decl);
17617     }
17618   init = RECUR (init);
17619 
17620   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
17621     {
17622       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
17623       if (TREE_CODE (o) == TREE_LIST)
17624 	TREE_VEC_ELT (orig_declv, i)
17625 	  = tree_cons (RECUR (TREE_PURPOSE (o)),
17626 		       RECUR (TREE_VALUE (o)),
17627 		       NULL_TREE);
17628       else
17629 	TREE_VEC_ELT (orig_declv, i) = RECUR (o);
17630     }
17631 
17632   if (range_for)
17633     {
17634       tree this_pre_body = NULL_TREE;
17635       tree orig_init = NULL_TREE;
17636       tree orig_decl = NULL_TREE;
17637       cp_convert_omp_range_for (this_pre_body, NULL, decl, orig_decl, init,
17638 				orig_init, cond, incr);
17639       if (orig_decl)
17640 	{
17641 	  if (orig_declv == NULL_TREE)
17642 	    orig_declv = copy_node (declv);
17643 	  TREE_VEC_ELT (orig_declv, i) = orig_decl;
17644 	  ret = true;
17645 	}
17646       else if (orig_declv)
17647 	TREE_VEC_ELT (orig_declv, i) = decl;
17648     }
17649 
17650   tree auto_node = type_uses_auto (TREE_TYPE (decl));
17651   if (!range_for && auto_node && init)
17652     TREE_TYPE (decl)
17653       = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
17654 
17655   gcc_assert (!type_dependent_expression_p (decl));
17656 
17657   if (!CLASS_TYPE_P (TREE_TYPE (decl)) || range_for)
17658     {
17659       if (decl_expr)
17660 	{
17661 	  /* Declare the variable, but don't let that initialize it.  */
17662 	  tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
17663 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
17664 	  RECUR (decl_expr);
17665 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
17666 	}
17667 
17668       if (!range_for)
17669 	{
17670 	  cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
17671 	  incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17672 	  if (TREE_CODE (incr) == MODIFY_EXPR)
17673 	    {
17674 	      tree lhs = RECUR (TREE_OPERAND (incr, 0));
17675 	      tree rhs = RECUR (TREE_OPERAND (incr, 1));
17676 	      incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
17677 					  NOP_EXPR, rhs, complain);
17678 	    }
17679 	  else
17680 	    incr = RECUR (incr);
17681 	  if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
17682 	    TREE_VEC_ELT (orig_declv, i) = decl;
17683 	}
17684       TREE_VEC_ELT (declv, i) = decl;
17685       TREE_VEC_ELT (initv, i) = init;
17686       TREE_VEC_ELT (condv, i) = cond;
17687       TREE_VEC_ELT (incrv, i) = incr;
17688       return ret;
17689     }
17690 
17691   if (decl_expr)
17692     {
17693       /* Declare and initialize the variable.  */
17694       RECUR (decl_expr);
17695       init = NULL_TREE;
17696     }
17697   else if (init)
17698     {
17699       tree *pc;
17700       int j;
17701       for (j = ((omp_parallel_combined_clauses == NULL
17702 		|| TREE_CODE (t) == OMP_LOOP) ? 1 : 0); j < 2; j++)
17703 	{
17704 	  for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
17705 	    {
17706 	      if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
17707 		  && OMP_CLAUSE_DECL (*pc) == decl)
17708 		break;
17709 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
17710 		       && OMP_CLAUSE_DECL (*pc) == decl)
17711 		{
17712 		  if (j)
17713 		    break;
17714 		  /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
17715 		  tree c = *pc;
17716 		  *pc = OMP_CLAUSE_CHAIN (c);
17717 		  OMP_CLAUSE_CHAIN (c) = *clauses;
17718 		  *clauses = c;
17719 		}
17720 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
17721 		       && OMP_CLAUSE_DECL (*pc) == decl)
17722 		{
17723 		  error ("iteration variable %qD should not be firstprivate",
17724 			 decl);
17725 		  *pc = OMP_CLAUSE_CHAIN (*pc);
17726 		}
17727 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
17728 		       && OMP_CLAUSE_DECL (*pc) == decl)
17729 		{
17730 		  error ("iteration variable %qD should not be reduction",
17731 			 decl);
17732 		  *pc = OMP_CLAUSE_CHAIN (*pc);
17733 		}
17734 	      else
17735 		pc = &OMP_CLAUSE_CHAIN (*pc);
17736 	    }
17737 	  if (*pc)
17738 	    break;
17739 	}
17740       if (*pc == NULL_TREE)
17741 	{
17742 	  tree c = build_omp_clause (input_location,
17743 				     TREE_CODE (t) == OMP_LOOP
17744 				     ? OMP_CLAUSE_LASTPRIVATE
17745 				     : OMP_CLAUSE_PRIVATE);
17746 	  OMP_CLAUSE_DECL (c) = decl;
17747 	  c = finish_omp_clauses (c, C_ORT_OMP);
17748 	  if (c)
17749 	    {
17750 	      OMP_CLAUSE_CHAIN (c) = *clauses;
17751 	      *clauses = c;
17752 	    }
17753 	}
17754     }
17755   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
17756   if (COMPARISON_CLASS_P (cond))
17757     {
17758       tree op0 = RECUR (TREE_OPERAND (cond, 0));
17759       tree op1 = RECUR (TREE_OPERAND (cond, 1));
17760       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
17761     }
17762   else
17763     cond = RECUR (cond);
17764   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
17765   switch (TREE_CODE (incr))
17766     {
17767     case PREINCREMENT_EXPR:
17768     case PREDECREMENT_EXPR:
17769     case POSTINCREMENT_EXPR:
17770     case POSTDECREMENT_EXPR:
17771       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
17772 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
17773       break;
17774     case MODIFY_EXPR:
17775       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
17776 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
17777 	{
17778 	  tree rhs = TREE_OPERAND (incr, 1);
17779 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
17780 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
17781 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
17782 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17783 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
17784 				 rhs0, rhs1));
17785 	}
17786       else
17787 	incr = RECUR (incr);
17788       break;
17789     case MODOP_EXPR:
17790       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
17791 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
17792 	{
17793 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
17794 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17795 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
17796 				 TREE_TYPE (decl), lhs,
17797 				 RECUR (TREE_OPERAND (incr, 2))));
17798 	}
17799       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
17800 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
17801 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
17802 	{
17803 	  tree rhs = TREE_OPERAND (incr, 2);
17804 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
17805 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
17806 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
17807 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
17808 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
17809 				 rhs0, rhs1));
17810 	}
17811       else
17812 	incr = RECUR (incr);
17813       break;
17814     default:
17815       incr = RECUR (incr);
17816       break;
17817     }
17818 
17819   if (orig_declv && !OMP_FOR_ORIG_DECLS (t))
17820     TREE_VEC_ELT (orig_declv, i) = decl;
17821   TREE_VEC_ELT (declv, i) = decl;
17822   TREE_VEC_ELT (initv, i) = init;
17823   TREE_VEC_ELT (condv, i) = cond;
17824   TREE_VEC_ELT (incrv, i) = incr;
17825   return false;
17826 #undef RECUR
17827 }
17828 
17829 /* Helper function of tsubst_expr, find OMP_TEAMS inside
17830    of OMP_TARGET's body.  */
17831 
17832 static tree
tsubst_find_omp_teams(tree * tp,int * walk_subtrees,void *)17833 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
17834 {
17835   *walk_subtrees = 0;
17836   switch (TREE_CODE (*tp))
17837     {
17838     case OMP_TEAMS:
17839       return *tp;
17840     case BIND_EXPR:
17841     case STATEMENT_LIST:
17842       *walk_subtrees = 1;
17843       break;
17844     default:
17845       break;
17846     }
17847   return NULL_TREE;
17848 }
17849 
17850 /* Helper function for tsubst_expr.  For decomposition declaration
17851    artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
17852    also the corresponding decls representing the identifiers
17853    of the decomposition declaration.  Return DECL if successful
17854    or error_mark_node otherwise, set *FIRST to the first decl
17855    in the list chained through DECL_CHAIN and *CNT to the number
17856    of such decls.  */
17857 
17858 static tree
tsubst_decomp_names(tree decl,tree pattern_decl,tree args,tsubst_flags_t complain,tree in_decl,tree * first,unsigned int * cnt)17859 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
17860 		     tsubst_flags_t complain, tree in_decl, tree *first,
17861 		     unsigned int *cnt)
17862 {
17863   tree decl2, decl3, prev = decl;
17864   *cnt = 0;
17865   gcc_assert (DECL_NAME (decl) == NULL_TREE);
17866   for (decl2 = DECL_CHAIN (pattern_decl);
17867        decl2
17868        && VAR_P (decl2)
17869        && DECL_DECOMPOSITION_P (decl2)
17870        && DECL_NAME (decl2);
17871        decl2 = DECL_CHAIN (decl2))
17872     {
17873       if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
17874 	{
17875 	  gcc_assert (errorcount);
17876 	  return error_mark_node;
17877 	}
17878       (*cnt)++;
17879       gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
17880       gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
17881       tree v = DECL_VALUE_EXPR (decl2);
17882       DECL_HAS_VALUE_EXPR_P (decl2) = 0;
17883       SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
17884       decl3 = tsubst (decl2, args, complain, in_decl);
17885       SET_DECL_VALUE_EXPR (decl2, v);
17886       DECL_HAS_VALUE_EXPR_P (decl2) = 1;
17887       if (VAR_P (decl3))
17888 	DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
17889       else
17890 	{
17891 	  gcc_assert (errorcount);
17892 	  decl = error_mark_node;
17893 	  continue;
17894 	}
17895       maybe_push_decl (decl3);
17896       if (error_operand_p (decl3))
17897 	decl = error_mark_node;
17898       else if (decl != error_mark_node
17899 	       && DECL_CHAIN (decl3) != prev
17900 	       && decl != prev)
17901 	{
17902 	  gcc_assert (errorcount);
17903 	  decl = error_mark_node;
17904 	}
17905       else
17906 	prev = decl3;
17907     }
17908   *first = prev;
17909   return decl;
17910 }
17911 
17912 /* Return the proper local_specialization for init-capture pack DECL.  */
17913 
17914 static tree
lookup_init_capture_pack(tree decl)17915 lookup_init_capture_pack (tree decl)
17916 {
17917   /* We handle normal pack captures by forwarding to the specialization of the
17918      captured parameter.  We can't do that for pack init-captures; we need them
17919      to have their own local_specialization.  We created the individual
17920      VAR_DECLs (if any) under build_capture_proxy, and we need to collect them
17921      when we process the DECL_EXPR for the pack init-capture in the template.
17922      So, how do we find them?  We don't know the capture proxy pack when
17923      building the individual resulting proxies, and we don't know the
17924      individual proxies when instantiating the pack.  What we have in common is
17925      the FIELD_DECL.
17926 
17927      So...when we instantiate the FIELD_DECL, we stick the result in
17928      local_specializations.  Then at the DECL_EXPR we look up that result, see
17929      how many elements it has, synthesize the names, and look them up.  */
17930 
17931   tree cname = DECL_NAME (decl);
17932   tree val = DECL_VALUE_EXPR (decl);
17933   tree field = TREE_OPERAND (val, 1);
17934   gcc_assert (TREE_CODE (field) == FIELD_DECL);
17935   tree fpack = retrieve_local_specialization (field);
17936   if (fpack == error_mark_node)
17937     return error_mark_node;
17938 
17939   int len = 1;
17940   tree vec = NULL_TREE;
17941   tree r = NULL_TREE;
17942   if (TREE_CODE (fpack) == TREE_VEC)
17943     {
17944       len = TREE_VEC_LENGTH (fpack);
17945       vec = make_tree_vec (len);
17946       r = make_node (NONTYPE_ARGUMENT_PACK);
17947       SET_ARGUMENT_PACK_ARGS (r, vec);
17948     }
17949   for (int i = 0; i < len; ++i)
17950     {
17951       tree ename = vec ? make_ith_pack_parameter_name (cname, i) : cname;
17952       tree elt = lookup_name_real (ename, 0, 0, true, 0, LOOKUP_NORMAL);
17953       if (vec)
17954 	TREE_VEC_ELT (vec, i) = elt;
17955       else
17956 	r = elt;
17957     }
17958   return r;
17959 }
17960 
17961 /* Like tsubst_copy for expressions, etc. but also does semantic
17962    processing.  */
17963 
17964 tree
tsubst_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)17965 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
17966 	     bool integral_constant_expression_p)
17967 {
17968 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
17969 #define RECUR(NODE)				\
17970   tsubst_expr ((NODE), args, complain, in_decl,	\
17971 	       integral_constant_expression_p)
17972 
17973   tree stmt, tmp;
17974   tree r;
17975   location_t loc;
17976 
17977   if (t == NULL_TREE || t == error_mark_node)
17978     return t;
17979 
17980   loc = input_location;
17981   if (location_t eloc = cp_expr_location (t))
17982     input_location = eloc;
17983   if (STATEMENT_CODE_P (TREE_CODE (t)))
17984     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
17985 
17986   switch (TREE_CODE (t))
17987     {
17988     case STATEMENT_LIST:
17989       {
17990 	tree_stmt_iterator i;
17991 	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
17992 	  RECUR (tsi_stmt (i));
17993 	break;
17994       }
17995 
17996     case CTOR_INITIALIZER:
17997       finish_mem_initializers (tsubst_initializer_list
17998 			       (TREE_OPERAND (t, 0), args));
17999       break;
18000 
18001     case RETURN_EXPR:
18002       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
18003       break;
18004 
18005     case CO_RETURN_EXPR:
18006       finish_co_return_stmt (input_location, RECUR (TREE_OPERAND (t, 0)));
18007       break;
18008 
18009     case CO_YIELD_EXPR:
18010       stmt = finish_co_yield_expr (input_location,
18011 				   RECUR (TREE_OPERAND (t, 0)));
18012       RETURN (stmt);
18013       break;
18014 
18015     case CO_AWAIT_EXPR:
18016       stmt = finish_co_await_expr (input_location,
18017 				   RECUR (TREE_OPERAND (t, 0)));
18018       RETURN (stmt);
18019       break;
18020 
18021     case EXPR_STMT:
18022       tmp = RECUR (EXPR_STMT_EXPR (t));
18023       if (EXPR_STMT_STMT_EXPR_RESULT (t))
18024 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
18025       else
18026 	finish_expr_stmt (tmp);
18027       break;
18028 
18029     case USING_STMT:
18030       finish_using_directive (USING_STMT_NAMESPACE (t), /*attribs=*/NULL_TREE);
18031       break;
18032 
18033     case DECL_EXPR:
18034       {
18035 	tree decl, pattern_decl;
18036 	tree init;
18037 
18038 	pattern_decl = decl = DECL_EXPR_DECL (t);
18039 	if (TREE_CODE (decl) == LABEL_DECL)
18040 	  finish_label_decl (DECL_NAME (decl));
18041 	else if (TREE_CODE (decl) == USING_DECL)
18042 	  {
18043 	    tree scope = USING_DECL_SCOPE (decl);
18044 	    tree name = DECL_NAME (decl);
18045 
18046 	    scope = tsubst (scope, args, complain, in_decl);
18047 	    finish_nonmember_using_decl (scope, name);
18048 	  }
18049 	else if (is_capture_proxy (decl)
18050 		 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
18051 	  {
18052 	    /* We're in tsubst_lambda_expr, we've already inserted a new
18053 	       capture proxy, so look it up and register it.  */
18054 	    tree inst;
18055 	    if (!DECL_PACK_P (decl))
18056 	      {
18057 		inst = lookup_name_real (DECL_NAME (decl), /*prefer_type*/0,
18058 					 /*nonclass*/1, /*block_p=*/true,
18059 					 /*ns_only*/0, LOOKUP_HIDDEN);
18060 		gcc_assert (inst != decl && is_capture_proxy (inst));
18061 	      }
18062 	    else if (is_normal_capture_proxy (decl))
18063 	      {
18064 		inst = (retrieve_local_specialization
18065 			(DECL_CAPTURED_VARIABLE (decl)));
18066 		gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK
18067 			    || DECL_PACK_P (inst));
18068 	      }
18069 	    else
18070 	      inst = lookup_init_capture_pack (decl);
18071 
18072 	    register_local_specialization (inst, decl);
18073 	    break;
18074 	  }
18075 	else if (DECL_PRETTY_FUNCTION_P (decl))
18076 	  decl = make_fname_decl (DECL_SOURCE_LOCATION (decl),
18077 				  DECL_NAME (decl),
18078 				  true/*DECL_PRETTY_FUNCTION_P (decl)*/);
18079 	else if (DECL_IMPLICIT_TYPEDEF_P (decl)
18080 		 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
18081 	  /* Don't copy the old closure; we'll create a new one in
18082 	     tsubst_lambda_expr.  */
18083 	  break;
18084 	else
18085 	  {
18086 	    init = DECL_INITIAL (decl);
18087 	    /* The following tsubst call will clear the DECL_TEMPLATE_INFO
18088 	       for local variables, so save if DECL was declared constinit.  */
18089 	    const bool constinit_p
18090 	      = (VAR_P (decl)
18091 		 && DECL_LANG_SPECIFIC (decl)
18092 		 && DECL_TEMPLATE_INFO (decl)
18093 		 && TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (decl)));
18094 	    decl = tsubst (decl, args, complain, in_decl);
18095 	    if (decl != error_mark_node)
18096 	      {
18097 		/* By marking the declaration as instantiated, we avoid
18098 		   trying to instantiate it.  Since instantiate_decl can't
18099 		   handle local variables, and since we've already done
18100 		   all that needs to be done, that's the right thing to
18101 		   do.  */
18102 		if (VAR_P (decl))
18103 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18104 		if (VAR_P (decl) && !DECL_NAME (decl)
18105 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
18106 		  /* Anonymous aggregates are a special case.  */
18107 		  finish_anon_union (decl);
18108 		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
18109 		  {
18110 		    DECL_CONTEXT (decl) = current_function_decl;
18111 		    if (DECL_NAME (decl) == this_identifier)
18112 		      {
18113 			tree lam = DECL_CONTEXT (current_function_decl);
18114 			lam = CLASSTYPE_LAMBDA_EXPR (lam);
18115 			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
18116 		      }
18117 		    insert_capture_proxy (decl);
18118 		  }
18119 		else if (DECL_IMPLICIT_TYPEDEF_P (t))
18120 		  /* We already did a pushtag.  */;
18121 		else if (TREE_CODE (decl) == FUNCTION_DECL
18122 			 && DECL_OMP_DECLARE_REDUCTION_P (decl)
18123 			 && DECL_FUNCTION_SCOPE_P (pattern_decl))
18124 		  {
18125 		    DECL_CONTEXT (decl) = NULL_TREE;
18126 		    pushdecl (decl);
18127 		    DECL_CONTEXT (decl) = current_function_decl;
18128 		    cp_check_omp_declare_reduction (decl);
18129 		  }
18130 		else
18131 		  {
18132 		    bool const_init = false;
18133 		    unsigned int cnt = 0;
18134 		    tree first = NULL_TREE, ndecl = error_mark_node;
18135 		    tree asmspec_tree = NULL_TREE;
18136 		    maybe_push_decl (decl);
18137 
18138 		    if (VAR_P (decl)
18139 			&& DECL_DECOMPOSITION_P (decl)
18140 			&& TREE_TYPE (pattern_decl) != error_mark_node)
18141 		      ndecl = tsubst_decomp_names (decl, pattern_decl, args,
18142 						   complain, in_decl, &first,
18143 						   &cnt);
18144 
18145 		    init = tsubst_init (init, decl, args, complain, in_decl);
18146 
18147 		    if (VAR_P (decl))
18148 		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
18149 				    (pattern_decl));
18150 
18151 		    if (ndecl != error_mark_node)
18152 		      cp_maybe_mangle_decomp (ndecl, first, cnt);
18153 
18154 		    if (VAR_P (decl) && DECL_HARD_REGISTER (pattern_decl))
18155 		      {
18156 			tree id = DECL_ASSEMBLER_NAME (pattern_decl);
18157 			const char *asmspec = IDENTIFIER_POINTER (id);
18158 			gcc_assert (asmspec[0] == '*');
18159 			asmspec_tree
18160 			  = build_string (IDENTIFIER_LENGTH (id) - 1,
18161 					  asmspec + 1);
18162 			TREE_TYPE (asmspec_tree) = char_array_type_node;
18163 		      }
18164 
18165 		    cp_finish_decl (decl, init, const_init, asmspec_tree,
18166 				    constinit_p ? LOOKUP_CONSTINIT : 0);
18167 
18168 		    if (ndecl != error_mark_node)
18169 		      cp_finish_decomp (ndecl, first, cnt);
18170 		  }
18171 	      }
18172 	  }
18173 
18174 	break;
18175       }
18176 
18177     case FOR_STMT:
18178       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
18179       RECUR (FOR_INIT_STMT (t));
18180       finish_init_stmt (stmt);
18181       tmp = RECUR (FOR_COND (t));
18182       finish_for_cond (tmp, stmt, false, 0);
18183       tmp = RECUR (FOR_EXPR (t));
18184       finish_for_expr (tmp, stmt);
18185       {
18186 	bool prev = note_iteration_stmt_body_start ();
18187 	RECUR (FOR_BODY (t));
18188 	note_iteration_stmt_body_end (prev);
18189       }
18190       finish_for_stmt (stmt);
18191       break;
18192 
18193     case RANGE_FOR_STMT:
18194       {
18195 	/* Construct another range_for, if this is not a final
18196 	   substitution (for inside a generic lambda of a
18197 	   template).  Otherwise convert to a regular for.  */
18198         tree decl, expr;
18199         stmt = (processing_template_decl
18200 		? begin_range_for_stmt (NULL_TREE, NULL_TREE)
18201 		: begin_for_stmt (NULL_TREE, NULL_TREE));
18202 	RECUR (RANGE_FOR_INIT_STMT (t));
18203         decl = RANGE_FOR_DECL (t);
18204         decl = tsubst (decl, args, complain, in_decl);
18205         maybe_push_decl (decl);
18206         expr = RECUR (RANGE_FOR_EXPR (t));
18207 
18208 	tree decomp_first = NULL_TREE;
18209 	unsigned decomp_cnt = 0;
18210 	if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
18211 	  decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
18212 				      complain, in_decl,
18213 				      &decomp_first, &decomp_cnt);
18214 
18215 	if (processing_template_decl)
18216 	  {
18217 	    RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
18218 	    RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
18219 	    finish_range_for_decl (stmt, decl, expr);
18220 	    if (decomp_first && decl != error_mark_node)
18221 	      cp_finish_decomp (decl, decomp_first, decomp_cnt);
18222 	  }
18223 	else
18224 	  {
18225 	    unsigned short unroll = (RANGE_FOR_UNROLL (t)
18226 				     ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
18227 	    stmt = cp_convert_range_for (stmt, decl, expr,
18228 					 decomp_first, decomp_cnt,
18229 					 RANGE_FOR_IVDEP (t), unroll);
18230 	  }
18231 
18232 	bool prev = note_iteration_stmt_body_start ();
18233         RECUR (RANGE_FOR_BODY (t));
18234 	note_iteration_stmt_body_end (prev);
18235         finish_for_stmt (stmt);
18236       }
18237       break;
18238 
18239     case WHILE_STMT:
18240       stmt = begin_while_stmt ();
18241       tmp = RECUR (WHILE_COND (t));
18242       finish_while_stmt_cond (tmp, stmt, false, 0);
18243       {
18244 	bool prev = note_iteration_stmt_body_start ();
18245 	RECUR (WHILE_BODY (t));
18246 	note_iteration_stmt_body_end (prev);
18247       }
18248       finish_while_stmt (stmt);
18249       break;
18250 
18251     case DO_STMT:
18252       stmt = begin_do_stmt ();
18253       {
18254 	bool prev = note_iteration_stmt_body_start ();
18255 	RECUR (DO_BODY (t));
18256 	note_iteration_stmt_body_end (prev);
18257       }
18258       finish_do_body (stmt);
18259       tmp = RECUR (DO_COND (t));
18260       finish_do_stmt (tmp, stmt, false, 0);
18261       break;
18262 
18263     case IF_STMT:
18264       stmt = begin_if_stmt ();
18265       IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
18266       if (IF_STMT_CONSTEXPR_P (t))
18267 	args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args);
18268       tmp = RECUR (IF_COND (t));
18269       tmp = finish_if_stmt_cond (tmp, stmt);
18270       if (IF_STMT_CONSTEXPR_P (t)
18271 	  && instantiation_dependent_expression_p (tmp))
18272 	{
18273 	  /* We're partially instantiating a generic lambda, but the condition
18274 	     of the constexpr if is still dependent.  Don't substitute into the
18275 	     branches now, just remember the template arguments.  */
18276 	  do_poplevel (IF_SCOPE (stmt));
18277 	  IF_COND (stmt) = IF_COND (t);
18278 	  THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
18279 	  ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
18280 	  IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
18281 	  add_stmt (stmt);
18282 	  break;
18283 	}
18284       if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
18285 	/* Don't instantiate the THEN_CLAUSE. */;
18286       else
18287 	{
18288 	  tree folded = fold_non_dependent_expr (tmp, complain);
18289 	  bool inhibit = integer_zerop (folded);
18290 	  if (inhibit)
18291 	    ++c_inhibit_evaluation_warnings;
18292 	  RECUR (THEN_CLAUSE (t));
18293 	  if (inhibit)
18294 	    --c_inhibit_evaluation_warnings;
18295 	}
18296       finish_then_clause (stmt);
18297 
18298       if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
18299 	/* Don't instantiate the ELSE_CLAUSE. */;
18300       else if (ELSE_CLAUSE (t))
18301 	{
18302 	  tree folded = fold_non_dependent_expr (tmp, complain);
18303 	  bool inhibit = integer_nonzerop (folded);
18304 	  begin_else_clause (stmt);
18305 	  if (inhibit)
18306 	    ++c_inhibit_evaluation_warnings;
18307 	  RECUR (ELSE_CLAUSE (t));
18308 	  if (inhibit)
18309 	    --c_inhibit_evaluation_warnings;
18310 	  finish_else_clause (stmt);
18311 	}
18312 
18313       finish_if_stmt (stmt);
18314       break;
18315 
18316     case BIND_EXPR:
18317       if (BIND_EXPR_BODY_BLOCK (t))
18318 	stmt = begin_function_body ();
18319       else
18320 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
18321 				    ? BCS_TRY_BLOCK : 0);
18322 
18323       RECUR (BIND_EXPR_BODY (t));
18324 
18325       if (BIND_EXPR_BODY_BLOCK (t))
18326 	finish_function_body (stmt);
18327       else
18328 	finish_compound_stmt (stmt);
18329       break;
18330 
18331     case BREAK_STMT:
18332       finish_break_stmt ();
18333       break;
18334 
18335     case CONTINUE_STMT:
18336       finish_continue_stmt ();
18337       break;
18338 
18339     case SWITCH_STMT:
18340       stmt = begin_switch_stmt ();
18341       tmp = RECUR (SWITCH_STMT_COND (t));
18342       finish_switch_cond (tmp, stmt);
18343       RECUR (SWITCH_STMT_BODY (t));
18344       finish_switch_stmt (stmt);
18345       break;
18346 
18347     case CASE_LABEL_EXPR:
18348       {
18349 	tree decl = CASE_LABEL (t);
18350 	tree low = RECUR (CASE_LOW (t));
18351 	tree high = RECUR (CASE_HIGH (t));
18352 	tree l = finish_case_label (EXPR_LOCATION (t), low, high);
18353 	if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
18354 	  {
18355 	    tree label = CASE_LABEL (l);
18356 	    FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18357 	    if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18358 	      cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18359 	  }
18360       }
18361       break;
18362 
18363     case LABEL_EXPR:
18364       {
18365 	tree decl = LABEL_EXPR_LABEL (t);
18366 	tree label;
18367 
18368 	label = finish_label_stmt (DECL_NAME (decl));
18369 	if (TREE_CODE (label) == LABEL_DECL)
18370 	  FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
18371 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
18372 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
18373       }
18374       break;
18375 
18376     case GOTO_EXPR:
18377       tmp = GOTO_DESTINATION (t);
18378       if (TREE_CODE (tmp) != LABEL_DECL)
18379 	/* Computed goto's must be tsubst'd into.  On the other hand,
18380 	   non-computed gotos must not be; the identifier in question
18381 	   will have no binding.  */
18382 	tmp = RECUR (tmp);
18383       else
18384 	tmp = DECL_NAME (tmp);
18385       finish_goto_stmt (tmp);
18386       break;
18387 
18388     case ASM_EXPR:
18389       {
18390 	tree string = RECUR (ASM_STRING (t));
18391 	tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
18392 						 complain, in_decl);
18393 	tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
18394 						complain, in_decl);
18395 	tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
18396 	 					  complain, in_decl);
18397 	tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
18398 						complain, in_decl);
18399 	tmp = finish_asm_stmt (EXPR_LOCATION (t), ASM_VOLATILE_P (t), string,
18400 			       outputs, inputs, clobbers, labels,
18401 			       ASM_INLINE_P (t));
18402 	tree asm_expr = tmp;
18403 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
18404 	  asm_expr = TREE_OPERAND (asm_expr, 0);
18405 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
18406       }
18407       break;
18408 
18409     case TRY_BLOCK:
18410       if (CLEANUP_P (t))
18411 	{
18412 	  stmt = begin_try_block ();
18413 	  RECUR (TRY_STMTS (t));
18414 	  finish_cleanup_try_block (stmt);
18415 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
18416 	}
18417       else
18418 	{
18419 	  tree compound_stmt = NULL_TREE;
18420 
18421 	  if (FN_TRY_BLOCK_P (t))
18422 	    stmt = begin_function_try_block (&compound_stmt);
18423 	  else
18424 	    stmt = begin_try_block ();
18425 
18426 	  RECUR (TRY_STMTS (t));
18427 
18428 	  if (FN_TRY_BLOCK_P (t))
18429 	    finish_function_try_block (stmt);
18430 	  else
18431 	    finish_try_block (stmt);
18432 
18433 	  RECUR (TRY_HANDLERS (t));
18434 	  if (FN_TRY_BLOCK_P (t))
18435 	    finish_function_handler_sequence (stmt, compound_stmt);
18436 	  else
18437 	    finish_handler_sequence (stmt);
18438 	}
18439       break;
18440 
18441     case HANDLER:
18442       {
18443 	tree decl = HANDLER_PARMS (t);
18444 
18445 	if (decl)
18446 	  {
18447 	    decl = tsubst (decl, args, complain, in_decl);
18448 	    /* Prevent instantiate_decl from trying to instantiate
18449 	       this variable.  We've already done all that needs to be
18450 	       done.  */
18451 	    if (decl != error_mark_node)
18452 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
18453 	  }
18454 	stmt = begin_handler ();
18455 	finish_handler_parms (decl, stmt);
18456 	RECUR (HANDLER_BODY (t));
18457 	finish_handler (stmt);
18458       }
18459       break;
18460 
18461     case TAG_DEFN:
18462       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
18463       if (CLASS_TYPE_P (tmp))
18464 	{
18465 	  /* Local classes are not independent templates; they are
18466 	     instantiated along with their containing function.  And this
18467 	     way we don't have to deal with pushing out of one local class
18468 	     to instantiate a member of another local class.  */
18469 	  /* Closures are handled by the LAMBDA_EXPR.  */
18470 	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
18471 	  complete_type (tmp);
18472 	  for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
18473 	    if ((VAR_P (fld)
18474 		 || (TREE_CODE (fld) == FUNCTION_DECL
18475 		     && !DECL_ARTIFICIAL (fld)))
18476 		&& DECL_TEMPLATE_INSTANTIATION (fld))
18477 	      instantiate_decl (fld, /*defer_ok=*/false,
18478 				/*expl_inst_class=*/false);
18479 	}
18480       break;
18481 
18482     case STATIC_ASSERT:
18483       {
18484 	tree condition;
18485 
18486 	++c_inhibit_evaluation_warnings;
18487         condition =
18488           tsubst_expr (STATIC_ASSERT_CONDITION (t),
18489                        args,
18490                        complain, in_decl,
18491                        /*integral_constant_expression_p=*/true);
18492 	--c_inhibit_evaluation_warnings;
18493 
18494         finish_static_assert (condition,
18495                               STATIC_ASSERT_MESSAGE (t),
18496                               STATIC_ASSERT_SOURCE_LOCATION (t),
18497                               /*member_p=*/false);
18498       }
18499       break;
18500 
18501     case OACC_KERNELS:
18502     case OACC_PARALLEL:
18503     case OACC_SERIAL:
18504       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
18505 				in_decl);
18506       stmt = begin_omp_parallel ();
18507       RECUR (OMP_BODY (t));
18508       finish_omp_construct (TREE_CODE (t), stmt, tmp);
18509       break;
18510 
18511     case OMP_PARALLEL:
18512       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
18513       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
18514 				complain, in_decl);
18515       if (OMP_PARALLEL_COMBINED (t))
18516 	omp_parallel_combined_clauses = &tmp;
18517       stmt = begin_omp_parallel ();
18518       RECUR (OMP_PARALLEL_BODY (t));
18519       gcc_assert (omp_parallel_combined_clauses == NULL);
18520       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
18521 	= OMP_PARALLEL_COMBINED (t);
18522       pop_omp_privatization_clauses (r);
18523       break;
18524 
18525     case OMP_TASK:
18526       if (OMP_TASK_BODY (t) == NULL_TREE)
18527 	{
18528 	  tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18529 				    complain, in_decl);
18530 	  t = copy_node (t);
18531 	  OMP_TASK_CLAUSES (t) = tmp;
18532 	  add_stmt (t);
18533 	  break;
18534 	}
18535       r = push_omp_privatization_clauses (false);
18536       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
18537 				complain, in_decl);
18538       stmt = begin_omp_task ();
18539       RECUR (OMP_TASK_BODY (t));
18540       finish_omp_task (tmp, stmt);
18541       pop_omp_privatization_clauses (r);
18542       break;
18543 
18544     case OMP_FOR:
18545     case OMP_LOOP:
18546     case OMP_SIMD:
18547     case OMP_DISTRIBUTE:
18548     case OMP_TASKLOOP:
18549     case OACC_LOOP:
18550       {
18551 	tree clauses, body, pre_body;
18552 	tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
18553 	tree orig_declv = NULL_TREE;
18554 	tree incrv = NULL_TREE;
18555 	enum c_omp_region_type ort = C_ORT_OMP;
18556 	bool any_range_for = false;
18557 	int i;
18558 
18559 	if (TREE_CODE (t) == OACC_LOOP)
18560 	  ort = C_ORT_ACC;
18561 
18562 	r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
18563 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
18564 				      in_decl);
18565 	if (OMP_FOR_INIT (t) != NULL_TREE)
18566 	  {
18567 	    declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18568 	    if (OMP_FOR_ORIG_DECLS (t))
18569 	      orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18570 	    initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18571 	    condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18572 	    incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
18573 	  }
18574 
18575 	keep_next_level (true);
18576 	stmt = begin_omp_structured_block ();
18577 
18578 	pre_body = push_stmt_list ();
18579 	RECUR (OMP_FOR_PRE_BODY (t));
18580 	pre_body = pop_stmt_list (pre_body);
18581 
18582 	if (OMP_FOR_INIT (t) != NULL_TREE)
18583 	  for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
18584 	    any_range_for
18585 	      |= tsubst_omp_for_iterator (t, i, declv, orig_declv, initv,
18586 					  condv, incrv, &clauses, args,
18587 					  complain, in_decl,
18588 					  integral_constant_expression_p);
18589 	omp_parallel_combined_clauses = NULL;
18590 
18591 	if (any_range_for)
18592 	  {
18593 	    gcc_assert (orig_declv);
18594 	    body = begin_omp_structured_block ();
18595 	    for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
18596 	      if (TREE_VEC_ELT (orig_declv, i) != TREE_VEC_ELT (declv, i)
18597 		  && TREE_CODE (TREE_VEC_ELT (orig_declv, i)) == TREE_LIST
18598 		  && TREE_CHAIN (TREE_VEC_ELT (orig_declv, i)))
18599 		cp_finish_omp_range_for (TREE_VEC_ELT (orig_declv, i),
18600 					 TREE_VEC_ELT (declv, i));
18601 	  }
18602 	else
18603 	  body = push_stmt_list ();
18604 	RECUR (OMP_FOR_BODY (t));
18605 	if (any_range_for)
18606 	  body = finish_omp_structured_block (body);
18607 	else
18608 	  body = pop_stmt_list (body);
18609 
18610 	if (OMP_FOR_INIT (t) != NULL_TREE)
18611 	  t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
18612 			      orig_declv, initv, condv, incrv, body, pre_body,
18613 			      NULL, clauses);
18614 	else
18615 	  {
18616 	    t = make_node (TREE_CODE (t));
18617 	    TREE_TYPE (t) = void_type_node;
18618 	    OMP_FOR_BODY (t) = body;
18619 	    OMP_FOR_PRE_BODY (t) = pre_body;
18620 	    OMP_FOR_CLAUSES (t) = clauses;
18621 	    SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
18622 	    add_stmt (t);
18623 	  }
18624 
18625 	add_stmt (finish_omp_for_block (finish_omp_structured_block (stmt),
18626 					t));
18627 	pop_omp_privatization_clauses (r);
18628       }
18629       break;
18630 
18631     case OMP_SECTIONS:
18632       omp_parallel_combined_clauses = NULL;
18633       /* FALLTHRU */
18634     case OMP_SINGLE:
18635     case OMP_TEAMS:
18636     case OMP_CRITICAL:
18637     case OMP_TASKGROUP:
18638     case OMP_SCAN:
18639       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
18640 					  && OMP_TEAMS_COMBINED (t));
18641       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
18642 				in_decl);
18643       if (TREE_CODE (t) == OMP_TEAMS)
18644 	{
18645 	  keep_next_level (true);
18646 	  stmt = begin_omp_structured_block ();
18647 	  RECUR (OMP_BODY (t));
18648 	  stmt = finish_omp_structured_block (stmt);
18649 	}
18650       else
18651 	{
18652 	  stmt = push_stmt_list ();
18653 	  RECUR (OMP_BODY (t));
18654 	  stmt = pop_stmt_list (stmt);
18655 	}
18656 
18657       t = copy_node (t);
18658       OMP_BODY (t) = stmt;
18659       OMP_CLAUSES (t) = tmp;
18660       add_stmt (t);
18661       pop_omp_privatization_clauses (r);
18662       break;
18663 
18664     case OMP_DEPOBJ:
18665       r = RECUR (OMP_DEPOBJ_DEPOBJ (t));
18666       if (OMP_DEPOBJ_CLAUSES (t) && OMP_DEPOBJ_CLAUSES (t) != error_mark_node)
18667 	{
18668 	  enum omp_clause_depend_kind kind = OMP_CLAUSE_DEPEND_SOURCE;
18669 	  if (TREE_CODE (OMP_DEPOBJ_CLAUSES (t)) == OMP_CLAUSE)
18670 	    {
18671 	      tmp = tsubst_omp_clauses (OMP_DEPOBJ_CLAUSES (t), C_ORT_OMP,
18672 					args, complain, in_decl);
18673 	      if (tmp == NULL_TREE)
18674 		tmp = error_mark_node;
18675 	    }
18676 	  else
18677 	    {
18678 	      kind = (enum omp_clause_depend_kind)
18679 		     tree_to_uhwi (OMP_DEPOBJ_CLAUSES (t));
18680 	      tmp = NULL_TREE;
18681 	    }
18682 	  finish_omp_depobj (EXPR_LOCATION (t), r, kind, tmp);
18683 	}
18684       else
18685 	finish_omp_depobj (EXPR_LOCATION (t), r,
18686 			   OMP_CLAUSE_DEPEND_SOURCE,
18687 			   OMP_DEPOBJ_CLAUSES (t));
18688       break;
18689 
18690     case OACC_DATA:
18691     case OMP_TARGET_DATA:
18692     case OMP_TARGET:
18693       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
18694 				? C_ORT_ACC : C_ORT_OMP, args, complain,
18695 				in_decl);
18696       keep_next_level (true);
18697       stmt = begin_omp_structured_block ();
18698 
18699       RECUR (OMP_BODY (t));
18700       stmt = finish_omp_structured_block (stmt);
18701 
18702       t = copy_node (t);
18703       OMP_BODY (t) = stmt;
18704       OMP_CLAUSES (t) = tmp;
18705       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
18706 	{
18707 	  tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
18708 	  if (teams)
18709 	    {
18710 	      /* For combined target teams, ensure the num_teams and
18711 		 thread_limit clause expressions are evaluated on the host,
18712 		 before entering the target construct.  */
18713 	      tree c;
18714 	      for (c = OMP_TEAMS_CLAUSES (teams);
18715 		   c; c = OMP_CLAUSE_CHAIN (c))
18716 		if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
18717 		     || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
18718 		    && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
18719 		  {
18720 		    tree expr = OMP_CLAUSE_OPERAND (c, 0);
18721 		    expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
18722 		    if (expr == error_mark_node)
18723 		      continue;
18724 		    tmp = TARGET_EXPR_SLOT (expr);
18725 		    add_stmt (expr);
18726 		    OMP_CLAUSE_OPERAND (c, 0) = expr;
18727 		    tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
18728 						OMP_CLAUSE_FIRSTPRIVATE);
18729 		    OMP_CLAUSE_DECL (tc) = tmp;
18730 		    OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
18731 		    OMP_TARGET_CLAUSES (t) = tc;
18732 		  }
18733 	    }
18734 	}
18735       add_stmt (t);
18736       break;
18737 
18738     case OACC_DECLARE:
18739       t = copy_node (t);
18740       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
18741 				complain, in_decl);
18742       OACC_DECLARE_CLAUSES (t) = tmp;
18743       add_stmt (t);
18744       break;
18745 
18746     case OMP_TARGET_UPDATE:
18747     case OMP_TARGET_ENTER_DATA:
18748     case OMP_TARGET_EXIT_DATA:
18749       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
18750 				complain, in_decl);
18751       t = copy_node (t);
18752       OMP_STANDALONE_CLAUSES (t) = tmp;
18753       add_stmt (t);
18754       break;
18755 
18756     case OACC_CACHE:
18757     case OACC_ENTER_DATA:
18758     case OACC_EXIT_DATA:
18759     case OACC_UPDATE:
18760       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
18761 				complain, in_decl);
18762       t = copy_node (t);
18763       OMP_STANDALONE_CLAUSES (t) = tmp;
18764       add_stmt (t);
18765       break;
18766 
18767     case OMP_ORDERED:
18768       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
18769 				complain, in_decl);
18770       stmt = push_stmt_list ();
18771       RECUR (OMP_BODY (t));
18772       stmt = pop_stmt_list (stmt);
18773 
18774       t = copy_node (t);
18775       OMP_BODY (t) = stmt;
18776       OMP_ORDERED_CLAUSES (t) = tmp;
18777       add_stmt (t);
18778       break;
18779 
18780     case OMP_MASTER:
18781       omp_parallel_combined_clauses = NULL;
18782       /* FALLTHRU */
18783     case OMP_SECTION:
18784       stmt = push_stmt_list ();
18785       RECUR (OMP_BODY (t));
18786       stmt = pop_stmt_list (stmt);
18787 
18788       t = copy_node (t);
18789       OMP_BODY (t) = stmt;
18790       add_stmt (t);
18791       break;
18792 
18793     case OMP_ATOMIC:
18794       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
18795       tmp = NULL_TREE;
18796       if (TREE_CODE (TREE_OPERAND (t, 0)) == OMP_CLAUSE)
18797 	tmp = tsubst_omp_clauses (TREE_OPERAND (t, 0), C_ORT_OMP, args,
18798 				  complain, in_decl);
18799       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
18800 	{
18801 	  tree op1 = TREE_OPERAND (t, 1);
18802 	  tree rhs1 = NULL_TREE;
18803 	  tree lhs, rhs;
18804 	  if (TREE_CODE (op1) == COMPOUND_EXPR)
18805 	    {
18806 	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
18807 	      op1 = TREE_OPERAND (op1, 1);
18808 	    }
18809 	  lhs = RECUR (TREE_OPERAND (op1, 0));
18810 	  rhs = RECUR (TREE_OPERAND (op1, 1));
18811 	  finish_omp_atomic (EXPR_LOCATION (t), OMP_ATOMIC, TREE_CODE (op1),
18812 			     lhs, rhs, NULL_TREE, NULL_TREE, rhs1, tmp,
18813 			     OMP_ATOMIC_MEMORY_ORDER (t));
18814 	}
18815       else
18816 	{
18817 	  tree op1 = TREE_OPERAND (t, 1);
18818 	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
18819 	  tree rhs1 = NULL_TREE;
18820 	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
18821 	  enum tree_code opcode = NOP_EXPR;
18822 	  if (code == OMP_ATOMIC_READ)
18823 	    {
18824 	      v = RECUR (TREE_OPERAND (op1, 0));
18825 	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
18826 	    }
18827 	  else if (code == OMP_ATOMIC_CAPTURE_OLD
18828 		   || code == OMP_ATOMIC_CAPTURE_NEW)
18829 	    {
18830 	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
18831 	      v = RECUR (TREE_OPERAND (op1, 0));
18832 	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
18833 	      if (TREE_CODE (op11) == COMPOUND_EXPR)
18834 		{
18835 		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
18836 		  op11 = TREE_OPERAND (op11, 1);
18837 		}
18838 	      lhs = RECUR (TREE_OPERAND (op11, 0));
18839 	      rhs = RECUR (TREE_OPERAND (op11, 1));
18840 	      opcode = TREE_CODE (op11);
18841 	      if (opcode == MODIFY_EXPR)
18842 		opcode = NOP_EXPR;
18843 	    }
18844 	  else
18845 	    {
18846 	      code = OMP_ATOMIC;
18847 	      lhs = RECUR (TREE_OPERAND (op1, 0));
18848 	      rhs = RECUR (TREE_OPERAND (op1, 1));
18849 	    }
18850 	  finish_omp_atomic (EXPR_LOCATION (t), code, opcode, lhs, rhs, v,
18851 			     lhs1, rhs1, tmp, OMP_ATOMIC_MEMORY_ORDER (t));
18852 	}
18853       break;
18854 
18855     case TRANSACTION_EXPR:
18856       {
18857 	int flags = 0;
18858 	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
18859 	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
18860 
18861         if (TRANSACTION_EXPR_IS_STMT (t))
18862           {
18863 	    tree body = TRANSACTION_EXPR_BODY (t);
18864 	    tree noex = NULL_TREE;
18865 	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
18866 	      {
18867 		noex = MUST_NOT_THROW_COND (body);
18868 		if (noex == NULL_TREE)
18869 		  noex = boolean_true_node;
18870 		body = TREE_OPERAND (body, 0);
18871 	      }
18872             stmt = begin_transaction_stmt (input_location, NULL, flags);
18873             RECUR (body);
18874             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
18875           }
18876         else
18877           {
18878             stmt = build_transaction_expr (EXPR_LOCATION (t),
18879 					   RECUR (TRANSACTION_EXPR_BODY (t)),
18880 					   flags, NULL_TREE);
18881             RETURN (stmt);
18882           }
18883       }
18884       break;
18885 
18886     case MUST_NOT_THROW_EXPR:
18887       {
18888 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18889 	tree cond = RECUR (MUST_NOT_THROW_COND (t));
18890 	RETURN (build_must_not_throw_expr (op0, cond));
18891       }
18892 
18893     case EXPR_PACK_EXPANSION:
18894       error ("invalid use of pack expansion expression");
18895       RETURN (error_mark_node);
18896 
18897     case NONTYPE_ARGUMENT_PACK:
18898       error ("use %<...%> to expand argument pack");
18899       RETURN (error_mark_node);
18900 
18901     case COMPOUND_EXPR:
18902       tmp = RECUR (TREE_OPERAND (t, 0));
18903       if (tmp == NULL_TREE)
18904 	/* If the first operand was a statement, we're done with it.  */
18905 	RETURN (RECUR (TREE_OPERAND (t, 1)));
18906       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
18907 				    RECUR (TREE_OPERAND (t, 1)),
18908 				    complain));
18909 
18910     case ANNOTATE_EXPR:
18911       tmp = RECUR (TREE_OPERAND (t, 0));
18912       RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
18913 			  TREE_TYPE (tmp), tmp,
18914 			  RECUR (TREE_OPERAND (t, 1)),
18915 			  RECUR (TREE_OPERAND (t, 2))));
18916 
18917     case PREDICT_EXPR:
18918       RETURN (add_stmt (copy_node (t)));
18919 
18920     default:
18921       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
18922 
18923       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
18924 				    /*function_p=*/false,
18925 				    integral_constant_expression_p));
18926     }
18927 
18928   RETURN (NULL_TREE);
18929  out:
18930   input_location = loc;
18931   return r;
18932 #undef RECUR
18933 #undef RETURN
18934 }
18935 
18936 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
18937    function.  For description of the body see comment above
18938    cp_parser_omp_declare_reduction_exprs.  */
18939 
18940 static void
tsubst_omp_udr(tree t,tree args,tsubst_flags_t complain,tree in_decl)18941 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
18942 {
18943   if (t == NULL_TREE || t == error_mark_node)
18944     return;
18945 
18946   gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
18947 
18948   tree_stmt_iterator tsi;
18949   int i;
18950   tree stmts[7];
18951   memset (stmts, 0, sizeof stmts);
18952   for (i = 0, tsi = tsi_start (t);
18953        i < 7 && !tsi_end_p (tsi);
18954        i++, tsi_next (&tsi))
18955     stmts[i] = tsi_stmt (tsi);
18956   gcc_assert (tsi_end_p (tsi));
18957 
18958   if (i >= 3)
18959     {
18960       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
18961 		  && TREE_CODE (stmts[1]) == DECL_EXPR);
18962       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
18963 			     args, complain, in_decl);
18964       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
18965 			    args, complain, in_decl);
18966       DECL_CONTEXT (omp_out) = current_function_decl;
18967       DECL_CONTEXT (omp_in) = current_function_decl;
18968       keep_next_level (true);
18969       tree block = begin_omp_structured_block ();
18970       tsubst_expr (stmts[2], args, complain, in_decl, false);
18971       block = finish_omp_structured_block (block);
18972       block = maybe_cleanup_point_expr_void (block);
18973       add_decl_expr (omp_out);
18974       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
18975 	TREE_NO_WARNING (omp_out) = 1;
18976       add_decl_expr (omp_in);
18977       finish_expr_stmt (block);
18978     }
18979   if (i >= 6)
18980     {
18981       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
18982 		  && TREE_CODE (stmts[4]) == DECL_EXPR);
18983       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
18984 			      args, complain, in_decl);
18985       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
18986 			      args, complain, in_decl);
18987       DECL_CONTEXT (omp_priv) = current_function_decl;
18988       DECL_CONTEXT (omp_orig) = current_function_decl;
18989       keep_next_level (true);
18990       tree block = begin_omp_structured_block ();
18991       tsubst_expr (stmts[5], args, complain, in_decl, false);
18992       block = finish_omp_structured_block (block);
18993       block = maybe_cleanup_point_expr_void (block);
18994       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
18995       add_decl_expr (omp_priv);
18996       add_decl_expr (omp_orig);
18997       finish_expr_stmt (block);
18998       if (i == 7)
18999 	add_decl_expr (omp_orig);
19000     }
19001 }
19002 
19003 /* T is a postfix-expression that is not being used in a function
19004    call.  Return the substituted version of T.  */
19005 
19006 static tree
tsubst_non_call_postfix_expression(tree t,tree args,tsubst_flags_t complain,tree in_decl)19007 tsubst_non_call_postfix_expression (tree t, tree args,
19008 				    tsubst_flags_t complain,
19009 				    tree in_decl)
19010 {
19011   if (TREE_CODE (t) == SCOPE_REF)
19012     t = tsubst_qualified_id (t, args, complain, in_decl,
19013 			     /*done=*/false, /*address_p=*/false);
19014   else
19015     t = tsubst_copy_and_build (t, args, complain, in_decl,
19016 			       /*function_p=*/false,
19017 			       /*integral_constant_expression_p=*/false);
19018 
19019   return t;
19020 }
19021 
19022 /* Subroutine of tsubst_lambda_expr: add the FIELD/INIT capture pair to the
19023    LAMBDA_EXPR_CAPTURE_LIST passed in LIST.  Do deduction for a previously
19024    dependent init-capture.  */
19025 
19026 static void
prepend_one_capture(tree field,tree init,tree & list,tsubst_flags_t complain)19027 prepend_one_capture (tree field, tree init, tree &list,
19028 		     tsubst_flags_t complain)
19029 {
19030   if (tree auto_node = type_uses_auto (TREE_TYPE (field)))
19031     {
19032       tree type = NULL_TREE;
19033       if (!init)
19034 	{
19035 	  if (complain & tf_error)
19036 	    error ("empty initializer in lambda init-capture");
19037 	  init = error_mark_node;
19038 	}
19039       else if (TREE_CODE (init) == TREE_LIST)
19040 	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19041       if (!type)
19042 	type = do_auto_deduction (TREE_TYPE (field), init, auto_node, complain);
19043       TREE_TYPE (field) = type;
19044       cp_apply_type_quals_to_decl (cp_type_quals (type), field);
19045     }
19046   list = tree_cons (field, init, list);
19047 }
19048 
19049 /* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
19050    instantiation context.  Instantiating a pack expansion containing a lambda
19051    might result in multiple lambdas all based on the same lambda in the
19052    template.  */
19053 
19054 tree
tsubst_lambda_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl)19055 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
19056 {
19057   tree oldfn = lambda_function (t);
19058   in_decl = oldfn;
19059 
19060   tree r = build_lambda_expr ();
19061 
19062   LAMBDA_EXPR_LOCATION (r)
19063     = LAMBDA_EXPR_LOCATION (t);
19064   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
19065     = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
19066   LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
19067   LAMBDA_EXPR_INSTANTIATED (r) = true;
19068 
19069   if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
19070     /* A lambda in a default argument outside a class gets no
19071        LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI.  But
19072        tsubst_default_argument calls start_lambda_scope, so we need to
19073        specifically ignore it here, and use the global scope.  */
19074     record_null_lambda_scope (r);
19075   else
19076     record_lambda_scope (r);
19077 
19078   gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
19079 	      && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
19080 
19081   vec<tree,va_gc>* field_packs = NULL;
19082 
19083   for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
19084        cap = TREE_CHAIN (cap))
19085     {
19086       tree ofield = TREE_PURPOSE (cap);
19087       tree init = TREE_VALUE (cap);
19088       if (PACK_EXPANSION_P (init))
19089 	init = tsubst_pack_expansion (init, args, complain, in_decl);
19090       else
19091 	init = tsubst_copy_and_build (init, args, complain, in_decl,
19092 				      /*fn*/false, /*constexpr*/false);
19093 
19094       if (init == error_mark_node)
19095 	return error_mark_node;
19096 
19097       if (init && TREE_CODE (init) == TREE_LIST)
19098 	init = build_x_compound_expr_from_list (init, ELK_INIT, complain);
19099 
19100       if (!processing_template_decl
19101 	  && init && TREE_CODE (init) != TREE_VEC
19102 	  && variably_modified_type_p (TREE_TYPE (init), NULL_TREE))
19103 	{
19104 	  /* For a VLA, simply tsubsting the field type won't work, we need to
19105 	     go through add_capture again.  XXX do we want to do this for all
19106 	     captures?  */
19107 	  tree name = (get_identifier
19108 		       (IDENTIFIER_POINTER (DECL_NAME (ofield)) + 2));
19109 	  tree ftype = TREE_TYPE (ofield);
19110 	  bool by_ref = (TYPE_REF_P (ftype)
19111 			 || (TREE_CODE (ftype) == DECLTYPE_TYPE
19112 			     && DECLTYPE_FOR_REF_CAPTURE (ftype)));
19113 	  add_capture (r, name, init, by_ref, !DECL_NORMAL_CAPTURE_P (ofield));
19114 	  continue;
19115 	}
19116 
19117       if (PACK_EXPANSION_P (ofield))
19118 	ofield = PACK_EXPANSION_PATTERN (ofield);
19119       tree field = tsubst_decl (ofield, args, complain);
19120 
19121       if (DECL_PACK_P (ofield) && !DECL_NORMAL_CAPTURE_P (ofield))
19122 	{
19123 	  /* Remember these for when we've pushed local_specializations.  */
19124 	  vec_safe_push (field_packs, ofield);
19125 	  vec_safe_push (field_packs, field);
19126 	}
19127 
19128       if (field == error_mark_node)
19129 	return error_mark_node;
19130 
19131       if (TREE_CODE (field) == TREE_VEC)
19132 	{
19133 	  int len = TREE_VEC_LENGTH (field);
19134 	  gcc_assert (TREE_CODE (init) == TREE_VEC
19135 		      && TREE_VEC_LENGTH (init) == len);
19136 	  for (int i = 0; i < len; ++i)
19137 	    prepend_one_capture (TREE_VEC_ELT (field, i),
19138 				 TREE_VEC_ELT (init, i),
19139 				 LAMBDA_EXPR_CAPTURE_LIST (r),
19140 				 complain);
19141 	}
19142       else
19143 	{
19144 	  prepend_one_capture (field, init, LAMBDA_EXPR_CAPTURE_LIST (r),
19145 			       complain);
19146 
19147 	  if (id_equal (DECL_NAME (field), "__this"))
19148 	    LAMBDA_EXPR_THIS_CAPTURE (r) = field;
19149 	}
19150     }
19151 
19152   tree type = begin_lambda_type (r);
19153   if (type == error_mark_node)
19154     return error_mark_node;
19155 
19156   /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
19157   determine_visibility (TYPE_NAME (type));
19158 
19159   register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
19160 
19161   tree oldtmpl = (generic_lambda_fn_p (oldfn)
19162 		  ? DECL_TI_TEMPLATE (oldfn)
19163 		  : NULL_TREE);
19164 
19165   tree fntype = static_fn_type (oldfn);
19166   if (oldtmpl)
19167     ++processing_template_decl;
19168   fntype = tsubst (fntype, args, complain, in_decl);
19169   if (oldtmpl)
19170     --processing_template_decl;
19171 
19172   if (fntype == error_mark_node)
19173     r = error_mark_node;
19174   else
19175     {
19176       /* The body of a lambda-expression is not a subexpression of the
19177 	 enclosing expression.  Parms are to have DECL_CHAIN tsubsted,
19178 	 which would be skipped if cp_unevaluated_operand.  */
19179       cp_evaluated ev;
19180 
19181       /* Fix the type of 'this'.  */
19182       fntype = build_memfn_type (fntype, type,
19183 				 type_memfn_quals (fntype),
19184 				 type_memfn_rqual (fntype));
19185       tree fn, tmpl;
19186       if (oldtmpl)
19187 	{
19188 	  tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
19189 	  if (tmpl == error_mark_node)
19190 	    {
19191 	      r = error_mark_node;
19192 	      goto out;
19193 	    }
19194 	  fn = DECL_TEMPLATE_RESULT (tmpl);
19195 	  finish_member_declaration (tmpl);
19196 	}
19197       else
19198 	{
19199 	  tmpl = NULL_TREE;
19200 	  fn = tsubst_function_decl (oldfn, args, complain, fntype);
19201 	  if (fn == error_mark_node)
19202 	    {
19203 	      r = error_mark_node;
19204 	      goto out;
19205 	    }
19206 	  finish_member_declaration (fn);
19207 	}
19208 
19209       if (tree ci = get_constraints (oldfn))
19210 	{
19211 	  /* Substitute into the lambda's constraints.  */
19212 	  if (oldtmpl)
19213 	    ++processing_template_decl;
19214 	  ci = tsubst_constraint_info (ci, args, complain, in_decl);
19215 	  if (oldtmpl)
19216 	    --processing_template_decl;
19217 	  set_constraints (fn, ci);
19218 	}
19219 
19220       /* Let finish_function set this.  */
19221       DECL_DECLARED_CONSTEXPR_P (fn) = false;
19222 
19223       bool nested = cfun;
19224       if (nested)
19225 	push_function_context ();
19226       else
19227 	/* Still increment function_depth so that we don't GC in the
19228 	   middle of an expression.  */
19229 	++function_depth;
19230 
19231       local_specialization_stack s (lss_copy);
19232 
19233       tree body = start_lambda_function (fn, r);
19234 
19235       /* Now record them for lookup_init_capture_pack.  */
19236       int fplen = vec_safe_length (field_packs);
19237       for (int i = 0; i < fplen; )
19238 	{
19239 	  tree pack = (*field_packs)[i++];
19240 	  tree inst = (*field_packs)[i++];
19241 	  register_local_specialization (inst, pack);
19242 	}
19243       release_tree_vector (field_packs);
19244 
19245       register_parameter_specializations (oldfn, fn);
19246 
19247       if (oldtmpl)
19248 	{
19249 	  /* We might not partially instantiate some parts of the function, so
19250 	     copy these flags from the original template.  */
19251 	  language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
19252 	  current_function_returns_value = ol->returns_value;
19253 	  current_function_returns_null = ol->returns_null;
19254 	  current_function_returns_abnormally = ol->returns_abnormally;
19255 	  current_function_infinite_loop = ol->infinite_loop;
19256 	}
19257 
19258       /* [temp.deduct] A lambda-expression appearing in a function type or a
19259 	 template parameter is not considered part of the immediate context for
19260 	 the purposes of template argument deduction. */
19261       complain = tf_warning_or_error;
19262 
19263       tree saved = DECL_SAVED_TREE (oldfn);
19264       if (TREE_CODE (saved) == BIND_EXPR && BIND_EXPR_BODY_BLOCK (saved))
19265 	/* We already have a body block from start_lambda_function, we don't
19266 	   need another to confuse NRV (91217).  */
19267 	saved = BIND_EXPR_BODY (saved);
19268 
19269       tsubst_expr (saved, args, complain, r, /*constexpr*/false);
19270 
19271       finish_lambda_function (body);
19272 
19273       if (nested)
19274 	pop_function_context ();
19275       else
19276 	--function_depth;
19277 
19278       /* The capture list was built up in reverse order; fix that now.  */
19279       LAMBDA_EXPR_CAPTURE_LIST (r)
19280 	= nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
19281 
19282       LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
19283 
19284       maybe_add_lambda_conv_op (type);
19285     }
19286 
19287 out:
19288   finish_struct (type, /*attr*/NULL_TREE);
19289 
19290   insert_pending_capture_proxies ();
19291 
19292   return r;
19293 }
19294 
19295 /* Like tsubst but deals with expressions and performs semantic
19296    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)" or
19297    "F<TARGS> (ARGS)".  */
19298 
19299 tree
tsubst_copy_and_build(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool function_p,bool integral_constant_expression_p)19300 tsubst_copy_and_build (tree t,
19301 		       tree args,
19302 		       tsubst_flags_t complain,
19303 		       tree in_decl,
19304 		       bool function_p,
19305 		       bool integral_constant_expression_p)
19306 {
19307 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
19308 #define RECUR(NODE)						\
19309   tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
19310 			 /*function_p=*/false,			\
19311 			 integral_constant_expression_p)
19312 
19313   tree retval, op1;
19314   location_t save_loc;
19315 
19316   if (t == NULL_TREE || t == error_mark_node)
19317     return t;
19318 
19319   save_loc = input_location;
19320   if (location_t eloc = cp_expr_location (t))
19321     input_location = eloc;
19322 
19323   /* N3276 decltype magic only applies to calls at the top level or on the
19324      right side of a comma.  */
19325   tsubst_flags_t decltype_flag = (complain & tf_decltype);
19326   complain &= ~tf_decltype;
19327 
19328   switch (TREE_CODE (t))
19329     {
19330     case USING_DECL:
19331       t = DECL_NAME (t);
19332       /* Fall through.  */
19333     case IDENTIFIER_NODE:
19334       {
19335 	tree decl;
19336 	cp_id_kind idk;
19337 	bool non_integral_constant_expression_p;
19338 	const char *error_msg;
19339 
19340 	if (IDENTIFIER_CONV_OP_P (t))
19341 	  {
19342 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19343 	    t = make_conv_op_name (new_type);
19344 	  }
19345 
19346 	/* Look up the name.  */
19347 	decl = lookup_name (t);
19348 
19349 	/* By convention, expressions use ERROR_MARK_NODE to indicate
19350 	   failure, not NULL_TREE.  */
19351 	if (decl == NULL_TREE)
19352 	  decl = error_mark_node;
19353 
19354 	decl = finish_id_expression (t, decl, NULL_TREE,
19355 				     &idk,
19356 				     integral_constant_expression_p,
19357           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
19358 				     &non_integral_constant_expression_p,
19359 				     /*template_p=*/false,
19360 				     /*done=*/true,
19361 				     /*address_p=*/false,
19362 				     /*template_arg_p=*/false,
19363 				     &error_msg,
19364 				     input_location);
19365 	if (error_msg)
19366 	  error (error_msg);
19367 	if (!function_p && identifier_p (decl))
19368 	  {
19369 	    if (complain & tf_error)
19370 	      unqualified_name_lookup_error (decl);
19371 	    decl = error_mark_node;
19372 	  }
19373 	RETURN (decl);
19374       }
19375 
19376     case TEMPLATE_ID_EXPR:
19377       {
19378 	tree object;
19379 	tree templ = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
19380 					    complain, in_decl,
19381 					    function_p,
19382 					    integral_constant_expression_p);
19383 	tree targs = TREE_OPERAND (t, 1);
19384 
19385 	if (targs)
19386 	  targs = tsubst_template_args (targs, args, complain, in_decl);
19387 	if (targs == error_mark_node)
19388 	  RETURN (error_mark_node);
19389 
19390 	if (TREE_CODE (templ) == SCOPE_REF)
19391 	  {
19392 	    tree name = TREE_OPERAND (templ, 1);
19393 	    tree tid = lookup_template_function (name, targs);
19394 	    TREE_OPERAND (templ, 1) = tid;
19395 	    RETURN (templ);
19396 	  }
19397 
19398 	if (concept_definition_p (templ))
19399 	  {
19400 	    tree check = build_concept_check (templ, targs, complain);
19401 	    if (check == error_mark_node)
19402 	      RETURN (error_mark_node);
19403 
19404 	    tree id = unpack_concept_check (check);
19405 
19406 	    /* If we built a function concept check, return the underlying
19407 	       template-id. So we can evaluate it as a function call.  */
19408 	    if (function_concept_p (TREE_OPERAND (id, 0)))
19409 	      RETURN (id);
19410 
19411 	    RETURN (check);
19412 	  }
19413 
19414 	if (variable_template_p (templ))
19415 	  {
19416 	    tree r = lookup_and_finish_template_variable (templ, targs,
19417 							  complain);
19418 	    r = maybe_wrap_with_location (r, EXPR_LOCATION (t));
19419 	    RETURN (r);
19420 	  }
19421 
19422 	if (TREE_CODE (templ) == COMPONENT_REF)
19423 	  {
19424 	    object = TREE_OPERAND (templ, 0);
19425 	    templ = TREE_OPERAND (templ, 1);
19426 	  }
19427 	else
19428 	  object = NULL_TREE;
19429 
19430 	tree tid = lookup_template_function (templ, targs);
19431 
19432 	if (object)
19433 	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (tid),
19434 			 object, tid, NULL_TREE));
19435 	else if (identifier_p (templ))
19436 	  {
19437 	    /* C++20 P0846: we can encounter an IDENTIFIER_NODE here when
19438 	       name lookup found nothing when parsing the template name.  */
19439 	    gcc_assert (cxx_dialect >= cxx2a || seen_error ());
19440 	    RETURN (tid);
19441 	  }
19442 	else
19443 	  RETURN (baselink_for_fns (tid));
19444       }
19445 
19446     case INDIRECT_REF:
19447       {
19448 	tree r = RECUR (TREE_OPERAND (t, 0));
19449 
19450 	if (REFERENCE_REF_P (t))
19451 	  {
19452 	    /* A type conversion to reference type will be enclosed in
19453 	       such an indirect ref, but the substitution of the cast
19454 	       will have also added such an indirect ref.  */
19455 	    r = convert_from_reference (r);
19456 	  }
19457 	else
19458 	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
19459 				    complain|decltype_flag);
19460 
19461 	if (REF_PARENTHESIZED_P (t))
19462 	  r = force_paren_expr (r);
19463 
19464 	RETURN (r);
19465       }
19466 
19467     case NOP_EXPR:
19468       {
19469 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19470 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19471 	RETURN (build_nop (type, op0));
19472       }
19473 
19474     case IMPLICIT_CONV_EXPR:
19475       {
19476 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19477 	tree expr = RECUR (TREE_OPERAND (t, 0));
19478 	if (dependent_type_p (type) || type_dependent_expression_p (expr))
19479 	  {
19480 	    retval = copy_node (t);
19481 	    TREE_TYPE (retval) = type;
19482 	    TREE_OPERAND (retval, 0) = expr;
19483 	    RETURN (retval);
19484 	  }
19485 	if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
19486 	  /* We'll pass this to convert_nontype_argument again, we don't need
19487 	     to actually perform any conversion here.  */
19488 	  RETURN (expr);
19489 	int flags = LOOKUP_IMPLICIT;
19490 	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
19491 	  flags = LOOKUP_NORMAL;
19492 	if (IMPLICIT_CONV_EXPR_BRACED_INIT (t))
19493 	  flags |= LOOKUP_NO_NARROWING;
19494 	RETURN (perform_implicit_conversion_flags (type, expr, complain,
19495 						  flags));
19496       }
19497 
19498     case CONVERT_EXPR:
19499       {
19500 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19501 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19502 	if (op0 == error_mark_node)
19503 	  RETURN (error_mark_node);
19504 	RETURN (build1 (CONVERT_EXPR, type, op0));
19505       }
19506 
19507     case CAST_EXPR:
19508     case REINTERPRET_CAST_EXPR:
19509     case CONST_CAST_EXPR:
19510     case DYNAMIC_CAST_EXPR:
19511     case STATIC_CAST_EXPR:
19512       {
19513 	tree type;
19514 	tree op, r = NULL_TREE;
19515 
19516 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
19517 	if (integral_constant_expression_p
19518 	    && !cast_valid_in_integral_constant_expression_p (type))
19519 	  {
19520             if (complain & tf_error)
19521               error ("a cast to a type other than an integral or "
19522                      "enumeration type cannot appear in a constant-expression");
19523 	    RETURN (error_mark_node);
19524 	  }
19525 
19526 	op = RECUR (TREE_OPERAND (t, 0));
19527 
19528 	warning_sentinel s(warn_useless_cast);
19529 	warning_sentinel s2(warn_ignored_qualifiers);
19530 	switch (TREE_CODE (t))
19531 	  {
19532 	  case CAST_EXPR:
19533 	    r = build_functional_cast (input_location, type, op, complain);
19534 	    break;
19535 	  case REINTERPRET_CAST_EXPR:
19536 	    r = build_reinterpret_cast (input_location, type, op, complain);
19537 	    break;
19538 	  case CONST_CAST_EXPR:
19539 	    r = build_const_cast (input_location, type, op, complain);
19540 	    break;
19541 	  case DYNAMIC_CAST_EXPR:
19542 	    r = build_dynamic_cast (input_location, type, op, complain);
19543 	    break;
19544 	  case STATIC_CAST_EXPR:
19545 	    r = build_static_cast (input_location, type, op, complain);
19546 	    break;
19547 	  default:
19548 	    gcc_unreachable ();
19549 	  }
19550 
19551 	RETURN (r);
19552       }
19553 
19554     case POSTDECREMENT_EXPR:
19555     case POSTINCREMENT_EXPR:
19556       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19557 						args, complain, in_decl);
19558       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
19559 				complain|decltype_flag));
19560 
19561     case PREDECREMENT_EXPR:
19562     case PREINCREMENT_EXPR:
19563     case NEGATE_EXPR:
19564     case BIT_NOT_EXPR:
19565     case ABS_EXPR:
19566     case TRUTH_NOT_EXPR:
19567     case UNARY_PLUS_EXPR:  /* Unary + */
19568     case REALPART_EXPR:
19569     case IMAGPART_EXPR:
19570       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
19571 				RECUR (TREE_OPERAND (t, 0)),
19572 				complain|decltype_flag));
19573 
19574     case FIX_TRUNC_EXPR:
19575       gcc_unreachable ();
19576 
19577     case ADDR_EXPR:
19578       op1 = TREE_OPERAND (t, 0);
19579       if (TREE_CODE (op1) == LABEL_DECL)
19580 	RETURN (finish_label_address_expr (DECL_NAME (op1),
19581 					  EXPR_LOCATION (op1)));
19582       if (TREE_CODE (op1) == SCOPE_REF)
19583 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
19584 				   /*done=*/true, /*address_p=*/true);
19585       else
19586 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
19587 						  in_decl);
19588       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
19589 				complain|decltype_flag));
19590 
19591     case PLUS_EXPR:
19592     case MINUS_EXPR:
19593     case MULT_EXPR:
19594     case TRUNC_DIV_EXPR:
19595     case CEIL_DIV_EXPR:
19596     case FLOOR_DIV_EXPR:
19597     case ROUND_DIV_EXPR:
19598     case EXACT_DIV_EXPR:
19599     case BIT_AND_EXPR:
19600     case BIT_IOR_EXPR:
19601     case BIT_XOR_EXPR:
19602     case TRUNC_MOD_EXPR:
19603     case FLOOR_MOD_EXPR:
19604     case TRUTH_ANDIF_EXPR:
19605     case TRUTH_ORIF_EXPR:
19606     case TRUTH_AND_EXPR:
19607     case TRUTH_OR_EXPR:
19608     case RSHIFT_EXPR:
19609     case LSHIFT_EXPR:
19610     case EQ_EXPR:
19611     case NE_EXPR:
19612     case MAX_EXPR:
19613     case MIN_EXPR:
19614     case LE_EXPR:
19615     case GE_EXPR:
19616     case LT_EXPR:
19617     case GT_EXPR:
19618     case SPACESHIP_EXPR:
19619     case MEMBER_REF:
19620     case DOTSTAR_EXPR:
19621       {
19622 	/* If T was type-dependent, suppress warnings that depend on the range
19623 	   of the types involved.  */
19624 	++processing_template_decl;
19625 	const bool was_dep = (potential_constant_expression (t)
19626 			      ? value_dependent_expression_p (t)
19627 			      : type_dependent_expression_p (t));
19628 	--processing_template_decl;
19629 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19630 	tree op1 = RECUR (TREE_OPERAND (t, 1));
19631 
19632 	warning_sentinel s1(warn_type_limits, was_dep);
19633 	warning_sentinel s2(warn_div_by_zero, was_dep);
19634 	warning_sentinel s3(warn_logical_op, was_dep);
19635 	warning_sentinel s4(warn_tautological_compare, was_dep);
19636 
19637 	tree r = build_x_binary_op
19638 	  (input_location, TREE_CODE (t),
19639 	   op0,
19640 	   (TREE_NO_WARNING (TREE_OPERAND (t, 0))
19641 	    ? ERROR_MARK
19642 	    : TREE_CODE (TREE_OPERAND (t, 0))),
19643 	   op1,
19644 	   (TREE_NO_WARNING (TREE_OPERAND (t, 1))
19645 	    ? ERROR_MARK
19646 	    : TREE_CODE (TREE_OPERAND (t, 1))),
19647 	   /*overload=*/NULL,
19648 	   complain|decltype_flag);
19649 	if (EXPR_P (r) && TREE_NO_WARNING (t))
19650 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
19651 
19652 	RETURN (r);
19653       }
19654 
19655     case POINTER_PLUS_EXPR:
19656       {
19657 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19658 	if (op0 == error_mark_node)
19659 	  RETURN (error_mark_node);
19660 	tree op1 = RECUR (TREE_OPERAND (t, 1));
19661 	if (op1 == error_mark_node)
19662 	  RETURN (error_mark_node);
19663 	RETURN (fold_build_pointer_plus (op0, op1));
19664       }
19665 
19666     case SCOPE_REF:
19667       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
19668 				  /*address_p=*/false));
19669 
19670     case BASELINK:
19671       RETURN (tsubst_baselink (t, current_nonlambda_class_type (),
19672 			       args, complain, in_decl));
19673 
19674     case ARRAY_REF:
19675       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19676 						args, complain, in_decl);
19677       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
19678 				 RECUR (TREE_OPERAND (t, 1)),
19679 				 complain|decltype_flag));
19680 
19681     case SIZEOF_EXPR:
19682       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
19683 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
19684 	RETURN (tsubst_copy (t, args, complain, in_decl));
19685       /* Fall through */
19686 
19687     case ALIGNOF_EXPR:
19688       {
19689 	tree r;
19690 
19691 	op1 = TREE_OPERAND (t, 0);
19692 	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
19693 	  op1 = TREE_TYPE (op1);
19694 	bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
19695 			    && ALIGNOF_EXPR_STD_P (t));
19696         if (!args)
19697 	  {
19698 	    /* When there are no ARGS, we are trying to evaluate a
19699 	       non-dependent expression from the parser.  Trying to do
19700 	       the substitutions may not work.  */
19701 	    if (!TYPE_P (op1))
19702 	      op1 = TREE_TYPE (op1);
19703 	  }
19704 	else
19705 	  {
19706 	    ++cp_unevaluated_operand;
19707 	    ++c_inhibit_evaluation_warnings;
19708 	    if (TYPE_P (op1))
19709 	      op1 = tsubst (op1, args, complain, in_decl);
19710 	    else
19711 	      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
19712 					   /*function_p=*/false,
19713 					   /*integral_constant_expression_p=*/
19714 					   false);
19715 	    --cp_unevaluated_operand;
19716 	    --c_inhibit_evaluation_warnings;
19717 	  }
19718         if (TYPE_P (op1))
19719 	  r = cxx_sizeof_or_alignof_type (input_location,
19720 					  op1, TREE_CODE (t), std_alignof,
19721 					  complain & tf_error);
19722 	else
19723 	  r = cxx_sizeof_or_alignof_expr (input_location,
19724 					  op1, TREE_CODE (t),
19725 					  complain & tf_error);
19726 	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
19727 	  {
19728 	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
19729 	      {
19730 		if (!processing_template_decl && TYPE_P (op1))
19731 		  {
19732 		    r = build_min (SIZEOF_EXPR, size_type_node,
19733 				   build1 (NOP_EXPR, op1, error_mark_node));
19734 		    SIZEOF_EXPR_TYPE_P (r) = 1;
19735 		  }
19736 		else
19737 		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
19738 		TREE_SIDE_EFFECTS (r) = 0;
19739 		TREE_READONLY (r) = 1;
19740 	      }
19741 	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
19742 	  }
19743 	RETURN (r);
19744       }
19745 
19746     case AT_ENCODE_EXPR:
19747       {
19748 	op1 = TREE_OPERAND (t, 0);
19749 	++cp_unevaluated_operand;
19750 	++c_inhibit_evaluation_warnings;
19751 	op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
19752 				     /*function_p=*/false,
19753 				     /*integral_constant_expression_p=*/false);
19754 	--cp_unevaluated_operand;
19755 	--c_inhibit_evaluation_warnings;
19756 	RETURN (objc_build_encode_expr (op1));
19757       }
19758 
19759     case NOEXCEPT_EXPR:
19760       op1 = TREE_OPERAND (t, 0);
19761       ++cp_unevaluated_operand;
19762       ++c_inhibit_evaluation_warnings;
19763       ++cp_noexcept_operand;
19764       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
19765 				   /*function_p=*/false,
19766 				   /*integral_constant_expression_p=*/false);
19767       --cp_unevaluated_operand;
19768       --c_inhibit_evaluation_warnings;
19769       --cp_noexcept_operand;
19770       RETURN (finish_noexcept_expr (op1, complain));
19771 
19772     case MODOP_EXPR:
19773       {
19774 	warning_sentinel s(warn_div_by_zero);
19775 	tree lhs = RECUR (TREE_OPERAND (t, 0));
19776 	tree rhs = RECUR (TREE_OPERAND (t, 2));
19777 	tree r = build_x_modify_expr
19778 	  (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
19779 	   complain|decltype_flag);
19780 	/* TREE_NO_WARNING must be set if either the expression was
19781 	   parenthesized or it uses an operator such as >>= rather
19782 	   than plain assignment.  In the former case, it was already
19783 	   set and must be copied.  In the latter case,
19784 	   build_x_modify_expr sets it and it must not be reset
19785 	   here.  */
19786 	if (TREE_NO_WARNING (t))
19787 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
19788 
19789 	RETURN (r);
19790       }
19791 
19792     case ARROW_EXPR:
19793       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
19794 						args, complain, in_decl);
19795       /* Remember that there was a reference to this entity.  */
19796       if (DECL_P (op1)
19797 	  && !mark_used (op1, complain) && !(complain & tf_error))
19798 	RETURN (error_mark_node);
19799       RETURN (build_x_arrow (input_location, op1, complain));
19800 
19801     case NEW_EXPR:
19802       {
19803 	tree placement = RECUR (TREE_OPERAND (t, 0));
19804 	tree init = RECUR (TREE_OPERAND (t, 3));
19805 	vec<tree, va_gc> *placement_vec;
19806 	vec<tree, va_gc> *init_vec;
19807 	tree ret;
19808 	location_t loc = EXPR_LOCATION (t);
19809 
19810 	if (placement == NULL_TREE)
19811 	  placement_vec = NULL;
19812 	else
19813 	  {
19814 	    placement_vec = make_tree_vector ();
19815 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
19816 	      vec_safe_push (placement_vec, TREE_VALUE (placement));
19817 	  }
19818 
19819 	/* If there was an initializer in the original tree, but it
19820 	   instantiated to an empty list, then we should pass a
19821 	   non-NULL empty vector to tell build_new that it was an
19822 	   empty initializer() rather than no initializer.  This can
19823 	   only happen when the initializer is a pack expansion whose
19824 	   parameter packs are of length zero.  */
19825 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
19826 	  init_vec = NULL;
19827 	else
19828 	  {
19829 	    init_vec = make_tree_vector ();
19830 	    if (init == void_node)
19831 	      gcc_assert (init_vec != NULL);
19832 	    else
19833 	      {
19834 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
19835 		  vec_safe_push (init_vec, TREE_VALUE (init));
19836 	      }
19837 	  }
19838 
19839 	/* Avoid passing an enclosing decl to valid_array_size_p.  */
19840 	in_decl = NULL_TREE;
19841 
19842 	tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
19843 	tree op2 = RECUR (TREE_OPERAND (t, 2));
19844 	ret = build_new (loc, &placement_vec, op1, op2,
19845 			 &init_vec, NEW_EXPR_USE_GLOBAL (t),
19846 			 complain);
19847 
19848 	if (placement_vec != NULL)
19849 	  release_tree_vector (placement_vec);
19850 	if (init_vec != NULL)
19851 	  release_tree_vector (init_vec);
19852 
19853 	RETURN (ret);
19854       }
19855 
19856     case DELETE_EXPR:
19857       {
19858 	tree op0 = RECUR (TREE_OPERAND (t, 0));
19859 	tree op1 = RECUR (TREE_OPERAND (t, 1));
19860 	RETURN (delete_sanity (input_location, op0, op1,
19861 			       DELETE_EXPR_USE_VEC (t),
19862 			       DELETE_EXPR_USE_GLOBAL (t),
19863 			       complain));
19864       }
19865 
19866     case COMPOUND_EXPR:
19867       {
19868 	tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
19869 					  complain & ~tf_decltype, in_decl,
19870 					  /*function_p=*/false,
19871 					  integral_constant_expression_p);
19872 	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
19873 				       op0,
19874 				       RECUR (TREE_OPERAND (t, 1)),
19875 				       complain|decltype_flag));
19876       }
19877 
19878     case CALL_EXPR:
19879       {
19880 	tree function;
19881 	unsigned int nargs, i;
19882 	bool qualified_p;
19883 	bool koenig_p;
19884 	tree ret;
19885 
19886 	function = CALL_EXPR_FN (t);
19887 	/* Internal function with no arguments.  */
19888 	if (function == NULL_TREE && call_expr_nargs (t) == 0)
19889 	  RETURN (t);
19890 
19891 	/* When we parsed the expression, we determined whether or
19892 	   not Koenig lookup should be performed.  */
19893 	koenig_p = KOENIG_LOOKUP_P (t);
19894 	if (function == NULL_TREE)
19895 	  {
19896 	    koenig_p = false;
19897 	    qualified_p = false;
19898 	  }
19899 	else if (TREE_CODE (function) == SCOPE_REF)
19900 	  {
19901 	    qualified_p = true;
19902 	    function = tsubst_qualified_id (function, args, complain, in_decl,
19903 					    /*done=*/false,
19904 					    /*address_p=*/false);
19905 	  }
19906 	else if (koenig_p && identifier_p (function))
19907 	  {
19908 	    /* Do nothing; calling tsubst_copy_and_build on an identifier
19909 	       would incorrectly perform unqualified lookup again.
19910 
19911 	       Note that we can also have an IDENTIFIER_NODE if the earlier
19912 	       unqualified lookup found a member function; in that case
19913 	       koenig_p will be false and we do want to do the lookup
19914 	       again to find the instantiated member function.
19915 
19916 	       FIXME but doing that causes c++/15272, so we need to stop
19917 	       using IDENTIFIER_NODE in that situation.  */
19918 	    qualified_p = false;
19919 	  }
19920 	else
19921 	  {
19922 	    if (TREE_CODE (function) == COMPONENT_REF)
19923 	      {
19924 		tree op = TREE_OPERAND (function, 1);
19925 
19926 		qualified_p = (TREE_CODE (op) == SCOPE_REF
19927 			       || (BASELINK_P (op)
19928 				   && BASELINK_QUALIFIED_P (op)));
19929 	      }
19930 	    else
19931 	      qualified_p = false;
19932 
19933 	    if (TREE_CODE (function) == ADDR_EXPR
19934 		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
19935 	      /* Avoid error about taking the address of a constructor.  */
19936 	      function = TREE_OPERAND (function, 0);
19937 
19938 	    function = tsubst_copy_and_build (function, args, complain,
19939 					      in_decl,
19940 					      !qualified_p,
19941 					      integral_constant_expression_p);
19942 
19943 	    if (BASELINK_P (function))
19944 	      qualified_p = true;
19945 	  }
19946 
19947 	nargs = call_expr_nargs (t);
19948 	releasing_vec call_args;
19949 	for (i = 0; i < nargs; ++i)
19950 	  {
19951 	    tree arg = CALL_EXPR_ARG (t, i);
19952 
19953 	    if (!PACK_EXPANSION_P (arg))
19954 	      vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
19955 	    else
19956 	      {
19957 		/* Expand the pack expansion and push each entry onto
19958 		   CALL_ARGS.  */
19959 		arg = tsubst_pack_expansion (arg, args, complain, in_decl);
19960 		if (TREE_CODE (arg) == TREE_VEC)
19961 		  {
19962 		    unsigned int len, j;
19963 
19964 		    len = TREE_VEC_LENGTH (arg);
19965 		    for (j = 0; j < len; ++j)
19966 		      {
19967 			tree value = TREE_VEC_ELT (arg, j);
19968 			if (value != NULL_TREE)
19969 			  value = convert_from_reference (value);
19970 			vec_safe_push (call_args, value);
19971 		      }
19972 		  }
19973 		else
19974 		  {
19975 		    /* A partial substitution.  Add one entry.  */
19976 		    vec_safe_push (call_args, arg);
19977 		  }
19978 	      }
19979 	  }
19980 
19981 	/* Stripped-down processing for a call in a thunk.  Specifically, in
19982 	   the thunk template for a generic lambda.  */
19983 	if (CALL_FROM_THUNK_P (t))
19984 	  {
19985 	    /* Now that we've expanded any packs, the number of call args
19986 	       might be different.  */
19987 	    unsigned int cargs = call_args->length ();
19988 	    tree thisarg = NULL_TREE;
19989 	    if (TREE_CODE (function) == COMPONENT_REF)
19990 	      {
19991 		thisarg = TREE_OPERAND (function, 0);
19992 		if (TREE_CODE (thisarg) == INDIRECT_REF)
19993 		  thisarg = TREE_OPERAND (thisarg, 0);
19994 		function = TREE_OPERAND (function, 1);
19995 		if (TREE_CODE (function) == BASELINK)
19996 		  function = BASELINK_FUNCTIONS (function);
19997 	      }
19998 	    /* We aren't going to do normal overload resolution, so force the
19999 	       template-id to resolve.  */
20000 	    function = resolve_nondeduced_context (function, complain);
20001 	    for (unsigned i = 0; i < cargs; ++i)
20002 	      {
20003 		/* In a thunk, pass through args directly, without any
20004 		   conversions.  */
20005 		tree arg = (*call_args)[i];
20006 		while (TREE_CODE (arg) != PARM_DECL)
20007 		  arg = TREE_OPERAND (arg, 0);
20008 		(*call_args)[i] = arg;
20009 	      }
20010 	    if (thisarg)
20011 	      {
20012 		/* If there are no other args, just push 'this'.  */
20013 		if (cargs == 0)
20014 		  vec_safe_push (call_args, thisarg);
20015 		else
20016 		  {
20017 		    /* Otherwise, shift the other args over to make room.  */
20018 		    tree last = (*call_args)[cargs - 1];
20019 		    vec_safe_push (call_args, last);
20020 		    for (int i = cargs - 1; i > 0; --i)
20021 		      (*call_args)[i] = (*call_args)[i - 1];
20022 		    (*call_args)[0] = thisarg;
20023 		  }
20024 	      }
20025 	    ret = build_call_a (function, call_args->length (),
20026 				call_args->address ());
20027 	    /* The thunk location is not interesting.  */
20028 	    SET_EXPR_LOCATION (ret, UNKNOWN_LOCATION);
20029 	    CALL_FROM_THUNK_P (ret) = true;
20030 	    if (CLASS_TYPE_P (TREE_TYPE (ret)))
20031 	      CALL_EXPR_RETURN_SLOT_OPT (ret) = true;
20032 
20033 	    RETURN (ret);
20034 	  }
20035 
20036 	/* We do not perform argument-dependent lookup if normal
20037 	   lookup finds a non-function, in accordance with the
20038 	   resolution of DR 218.  */
20039 	if (koenig_p
20040 	    && ((is_overloaded_fn (function)
20041 		 /* If lookup found a member function, the Koenig lookup is
20042 		    not appropriate, even if an unqualified-name was used
20043 		    to denote the function.  */
20044 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
20045 		|| identifier_p (function)
20046 		/* C++20 P0846: Lookup found nothing.  */
20047 		|| (TREE_CODE (function) == TEMPLATE_ID_EXPR
20048 		    && identifier_p (TREE_OPERAND (function, 0))))
20049 	    /* Only do this when substitution turns a dependent call
20050 	       into a non-dependent call.  */
20051 	    && type_dependent_expression_p_push (t)
20052 	    && !any_type_dependent_arguments_p (call_args))
20053 	  function = perform_koenig_lookup (function, call_args, tf_none);
20054 
20055 	if (function != NULL_TREE
20056 	    && (identifier_p (function)
20057 		|| (TREE_CODE (function) == TEMPLATE_ID_EXPR
20058 		    && identifier_p (TREE_OPERAND (function, 0))))
20059 	    && !any_type_dependent_arguments_p (call_args))
20060 	  {
20061 	    if (TREE_CODE (function) == TEMPLATE_ID_EXPR)
20062 	      function = TREE_OPERAND (function, 0);
20063 	    if (koenig_p && (complain & tf_warning_or_error))
20064 	      {
20065 		/* For backwards compatibility and good diagnostics, try
20066 		   the unqualified lookup again if we aren't in SFINAE
20067 		   context.  */
20068 		tree unq = (tsubst_copy_and_build
20069 			    (function, args, complain, in_decl, true,
20070 			     integral_constant_expression_p));
20071 		if (unq == error_mark_node)
20072 		  RETURN (error_mark_node);
20073 
20074 		if (unq != function)
20075 		  {
20076 		    /* In a lambda fn, we have to be careful to not
20077 		       introduce new this captures.  Legacy code can't
20078 		       be using lambdas anyway, so it's ok to be
20079 		       stricter.  */
20080 		    bool in_lambda = (current_class_type
20081 				      && LAMBDA_TYPE_P (current_class_type));
20082 		    char const *const msg
20083 		      = G_("%qD was not declared in this scope, "
20084 			   "and no declarations were found by "
20085 			   "argument-dependent lookup at the point "
20086 			   "of instantiation");
20087 
20088 		    bool diag = true;
20089 		    if (in_lambda)
20090 		      error_at (cp_expr_loc_or_input_loc (t),
20091 				msg, function);
20092 		    else
20093 		      diag = permerror (cp_expr_loc_or_input_loc (t),
20094 					msg, function);
20095 		    if (diag)
20096 		      {
20097 			tree fn = unq;
20098 
20099 			if (INDIRECT_REF_P (fn))
20100 			  fn = TREE_OPERAND (fn, 0);
20101 			if (is_overloaded_fn (fn))
20102 			  fn = get_first_fn (fn);
20103 
20104 			if (!DECL_P (fn))
20105 			  /* Can't say anything more.  */;
20106 			else if (DECL_CLASS_SCOPE_P (fn))
20107 			  {
20108 			    location_t loc = cp_expr_loc_or_input_loc (t);
20109 			    inform (loc,
20110 				    "declarations in dependent base %qT are "
20111 				    "not found by unqualified lookup",
20112 				    DECL_CLASS_CONTEXT (fn));
20113 			    if (current_class_ptr)
20114 			      inform (loc,
20115 				      "use %<this->%D%> instead", function);
20116 			    else
20117 			      inform (loc,
20118 				      "use %<%T::%D%> instead",
20119 				      current_class_name, function);
20120 			  }
20121 			else
20122 			  inform (DECL_SOURCE_LOCATION (fn),
20123 				  "%qD declared here, later in the "
20124 				  "translation unit", fn);
20125 			if (in_lambda)
20126 			  RETURN (error_mark_node);
20127 		      }
20128 
20129 		    function = unq;
20130 		  }
20131 	      }
20132 	    if (identifier_p (function))
20133 	      {
20134 		if (complain & tf_error)
20135 		  unqualified_name_lookup_error (function);
20136 		RETURN (error_mark_node);
20137 	      }
20138 	  }
20139 
20140 	/* Remember that there was a reference to this entity.  */
20141 	if (function != NULL_TREE
20142 	    && DECL_P (function)
20143 	    && !mark_used (function, complain) && !(complain & tf_error))
20144 	  RETURN (error_mark_node);
20145 
20146 	/* Put back tf_decltype for the actual call.  */
20147 	complain |= decltype_flag;
20148 
20149 	if (function == NULL_TREE)
20150 	  switch (CALL_EXPR_IFN (t))
20151 	    {
20152 	    case IFN_LAUNDER:
20153 	      gcc_assert (nargs == 1);
20154 	      if (vec_safe_length (call_args) != 1)
20155 		{
20156 		  error_at (cp_expr_loc_or_input_loc (t),
20157 			    "wrong number of arguments to "
20158 			    "%<__builtin_launder%>");
20159 		  ret = error_mark_node;
20160 		}
20161 	      else
20162 		ret = finish_builtin_launder (cp_expr_loc_or_input_loc (t),
20163 					      (*call_args)[0], complain);
20164 	      break;
20165 
20166 	    case IFN_VEC_CONVERT:
20167 	      gcc_assert (nargs == 1);
20168 	      if (vec_safe_length (call_args) != 1)
20169 		{
20170 		  error_at (cp_expr_loc_or_input_loc (t),
20171 			    "wrong number of arguments to "
20172 			    "%<__builtin_convertvector%>");
20173 		  ret = error_mark_node;
20174 		  break;
20175 		}
20176 	      ret = cp_build_vec_convert ((*call_args)[0], input_location,
20177 					  tsubst (TREE_TYPE (t), args,
20178 						  complain, in_decl),
20179 					  complain);
20180 	      if (TREE_CODE (ret) == VIEW_CONVERT_EXPR)
20181 		RETURN (ret);
20182 	      break;
20183 
20184 	    default:
20185 	      /* Unsupported internal function with arguments.  */
20186 	      gcc_unreachable ();
20187 	    }
20188 	else if (TREE_CODE (function) == OFFSET_REF
20189 		 || TREE_CODE (function) == DOTSTAR_EXPR
20190 		 || TREE_CODE (function) == MEMBER_REF)
20191 	  ret = build_offset_ref_call_from_tree (function, &call_args,
20192 						 complain);
20193 	else if (TREE_CODE (function) == COMPONENT_REF)
20194 	  {
20195 	    tree instance = TREE_OPERAND (function, 0);
20196 	    tree fn = TREE_OPERAND (function, 1);
20197 
20198 	    if (processing_template_decl
20199 		&& (type_dependent_expression_p (instance)
20200 		    || (!BASELINK_P (fn)
20201 			&& TREE_CODE (fn) != FIELD_DECL)
20202 		    || type_dependent_expression_p (fn)
20203 		    || any_type_dependent_arguments_p (call_args)))
20204 	      ret = build_min_nt_call_vec (function, call_args);
20205 	    else if (!BASELINK_P (fn))
20206 	      ret = finish_call_expr (function, &call_args,
20207 				       /*disallow_virtual=*/false,
20208 				       /*koenig_p=*/false,
20209 				       complain);
20210 	    else
20211 	      ret = (build_new_method_call
20212 		      (instance, fn,
20213 		       &call_args, NULL_TREE,
20214 		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
20215 		       /*fn_p=*/NULL,
20216 		       complain));
20217 	  }
20218 	else if (concept_check_p (function))
20219 	  {
20220 	    /* FUNCTION is a template-id referring to a concept definition.  */
20221 	    tree id = unpack_concept_check (function);
20222 	    tree tmpl = TREE_OPERAND (id, 0);
20223 	    tree args = TREE_OPERAND (id, 1);
20224 
20225 	    /* Calls to standard and variable concepts should have been
20226 	       previously diagnosed.  */
20227 	    gcc_assert (function_concept_p (tmpl));
20228 
20229 	    /* Ensure the result is wrapped as a call expression.  */
20230 	    ret = build_concept_check (tmpl, args, tf_warning_or_error);
20231 	  }
20232 	else
20233 	  ret = finish_call_expr (function, &call_args,
20234 				  /*disallow_virtual=*/qualified_p,
20235 				  koenig_p,
20236 				  complain);
20237 
20238 	if (ret != error_mark_node)
20239 	  {
20240 	    bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
20241 	    bool ord = CALL_EXPR_ORDERED_ARGS (t);
20242 	    bool rev = CALL_EXPR_REVERSE_ARGS (t);
20243 	    if (op || ord || rev)
20244 	      {
20245 		function = extract_call_expr (ret);
20246 		CALL_EXPR_OPERATOR_SYNTAX (function) = op;
20247 		CALL_EXPR_ORDERED_ARGS (function) = ord;
20248 		CALL_EXPR_REVERSE_ARGS (function) = rev;
20249 	      }
20250 	  }
20251 
20252 	RETURN (ret);
20253       }
20254 
20255     case COND_EXPR:
20256       {
20257 	tree cond = RECUR (TREE_OPERAND (t, 0));
20258 	cond = mark_rvalue_use (cond);
20259 	tree folded_cond = fold_non_dependent_expr (cond, complain);
20260 	tree exp1, exp2;
20261 
20262 	if (TREE_CODE (folded_cond) == INTEGER_CST)
20263 	  {
20264 	    if (integer_zerop (folded_cond))
20265 	      {
20266 		++c_inhibit_evaluation_warnings;
20267 		exp1 = RECUR (TREE_OPERAND (t, 1));
20268 		--c_inhibit_evaluation_warnings;
20269 		exp2 = RECUR (TREE_OPERAND (t, 2));
20270 	      }
20271 	    else
20272 	      {
20273 		exp1 = RECUR (TREE_OPERAND (t, 1));
20274 		++c_inhibit_evaluation_warnings;
20275 		exp2 = RECUR (TREE_OPERAND (t, 2));
20276 		--c_inhibit_evaluation_warnings;
20277 	      }
20278 	    cond = folded_cond;
20279 	  }
20280 	else
20281 	  {
20282 	    exp1 = RECUR (TREE_OPERAND (t, 1));
20283 	    exp2 = RECUR (TREE_OPERAND (t, 2));
20284 	  }
20285 
20286 	warning_sentinel s(warn_duplicated_branches);
20287 	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
20288 					 cond, exp1, exp2, complain));
20289       }
20290 
20291     case PSEUDO_DTOR_EXPR:
20292       {
20293 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20294 	tree op1 = RECUR (TREE_OPERAND (t, 1));
20295 	tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
20296 	RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
20297 					       input_location));
20298       }
20299 
20300     case TREE_LIST:
20301       {
20302 	tree purpose, value, chain;
20303 
20304 	if (t == void_list_node)
20305 	  RETURN (t);
20306 
20307         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
20308             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
20309           {
20310             /* We have pack expansions, so expand those and
20311                create a new list out of it.  */
20312             tree purposevec = NULL_TREE;
20313             tree valuevec = NULL_TREE;
20314             tree chain;
20315             int i, len = -1;
20316 
20317             /* Expand the argument expressions.  */
20318             if (TREE_PURPOSE (t))
20319               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
20320                                                  complain, in_decl);
20321             if (TREE_VALUE (t))
20322               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
20323                                                complain, in_decl);
20324 
20325             /* Build the rest of the list.  */
20326             chain = TREE_CHAIN (t);
20327             if (chain && chain != void_type_node)
20328               chain = RECUR (chain);
20329 
20330             /* Determine the number of arguments.  */
20331             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
20332               {
20333                 len = TREE_VEC_LENGTH (purposevec);
20334                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
20335               }
20336             else if (TREE_CODE (valuevec) == TREE_VEC)
20337               len = TREE_VEC_LENGTH (valuevec);
20338             else
20339               {
20340                 /* Since we only performed a partial substitution into
20341                    the argument pack, we only RETURN (a single list
20342                    node.  */
20343                 if (purposevec == TREE_PURPOSE (t)
20344                     && valuevec == TREE_VALUE (t)
20345                     && chain == TREE_CHAIN (t))
20346                   RETURN (t);
20347 
20348                 RETURN (tree_cons (purposevec, valuevec, chain));
20349               }
20350 
20351             /* Convert the argument vectors into a TREE_LIST */
20352             i = len;
20353             while (i > 0)
20354               {
20355                 /* Grab the Ith values.  */
20356                 i--;
20357                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
20358 		                     : NULL_TREE;
20359                 value
20360 		  = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
20361                              : NULL_TREE;
20362 
20363                 /* Build the list (backwards).  */
20364                 chain = tree_cons (purpose, value, chain);
20365               }
20366 
20367             RETURN (chain);
20368           }
20369 
20370 	purpose = TREE_PURPOSE (t);
20371 	if (purpose)
20372 	  purpose = RECUR (purpose);
20373 	value = TREE_VALUE (t);
20374 	if (value)
20375 	  value = RECUR (value);
20376 	chain = TREE_CHAIN (t);
20377 	if (chain && chain != void_type_node)
20378 	  chain = RECUR (chain);
20379 	if (purpose == TREE_PURPOSE (t)
20380 	    && value == TREE_VALUE (t)
20381 	    && chain == TREE_CHAIN (t))
20382 	  RETURN (t);
20383 	RETURN (tree_cons (purpose, value, chain));
20384       }
20385 
20386     case COMPONENT_REF:
20387       {
20388 	tree object;
20389 	tree object_type;
20390 	tree member;
20391 	tree r;
20392 
20393 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
20394 						     args, complain, in_decl);
20395 	/* Remember that there was a reference to this entity.  */
20396 	if (DECL_P (object)
20397 	    && !mark_used (object, complain) && !(complain & tf_error))
20398 	  RETURN (error_mark_node);
20399 	object_type = TREE_TYPE (object);
20400 
20401 	member = TREE_OPERAND (t, 1);
20402 	if (BASELINK_P (member))
20403 	  member = tsubst_baselink (member,
20404 				    non_reference (TREE_TYPE (object)),
20405 				    args, complain, in_decl);
20406 	else
20407 	  member = tsubst_copy (member, args, complain, in_decl);
20408 	if (member == error_mark_node)
20409 	  RETURN (error_mark_node);
20410 
20411 	if (TREE_CODE (member) == FIELD_DECL)
20412 	  {
20413 	    r = finish_non_static_data_member (member, object, NULL_TREE);
20414 	    if (TREE_CODE (r) == COMPONENT_REF)
20415 	      REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
20416 	    RETURN (r);
20417 	  }
20418 	else if (type_dependent_expression_p (object))
20419 	  /* We can't do much here.  */;
20420 	else if (!CLASS_TYPE_P (object_type))
20421 	  {
20422 	    if (scalarish_type_p (object_type))
20423 	      {
20424 		tree s = NULL_TREE;
20425 		tree dtor = member;
20426 
20427 		if (TREE_CODE (dtor) == SCOPE_REF)
20428 		  {
20429 		    s = TREE_OPERAND (dtor, 0);
20430 		    dtor = TREE_OPERAND (dtor, 1);
20431 		  }
20432 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
20433 		  {
20434 		    dtor = TREE_OPERAND (dtor, 0);
20435 		    if (TYPE_P (dtor))
20436 		      RETURN (finish_pseudo_destructor_expr
20437 			      (object, s, dtor, input_location));
20438 		  }
20439 	      }
20440 	  }
20441 	else if (TREE_CODE (member) == SCOPE_REF
20442 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
20443 	  {
20444 	    /* Lookup the template functions now that we know what the
20445 	       scope is.  */
20446 	    tree scope = TREE_OPERAND (member, 0);
20447 	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
20448 	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
20449 	    member = lookup_qualified_name (scope, tmpl,
20450 					    /*is_type_p=*/false,
20451 					    /*complain=*/false);
20452 	    if (BASELINK_P (member))
20453 	      {
20454 		BASELINK_FUNCTIONS (member)
20455 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
20456 			      args);
20457 		member = (adjust_result_of_qualified_name_lookup
20458 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
20459 			   object_type));
20460 	      }
20461 	    else
20462 	      {
20463 		qualified_name_lookup_error (scope, tmpl, member,
20464 					     input_location);
20465 		RETURN (error_mark_node);
20466 	      }
20467 	  }
20468 	else if (TREE_CODE (member) == SCOPE_REF
20469 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
20470 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
20471 	  {
20472 	    if (complain & tf_error)
20473 	      {
20474 		if (TYPE_P (TREE_OPERAND (member, 0)))
20475 		  error ("%qT is not a class or namespace",
20476 			 TREE_OPERAND (member, 0));
20477 		else
20478 		  error ("%qD is not a class or namespace",
20479 			 TREE_OPERAND (member, 0));
20480 	      }
20481 	    RETURN (error_mark_node);
20482 	  }
20483 
20484 	r = finish_class_member_access_expr (object, member,
20485 					     /*template_p=*/false,
20486 					     complain);
20487 	if (TREE_CODE (r) == COMPONENT_REF)
20488 	  REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
20489 	RETURN (r);
20490       }
20491 
20492     case THROW_EXPR:
20493       RETURN (build_throw
20494        (input_location, RECUR (TREE_OPERAND (t, 0))));
20495 
20496     case CONSTRUCTOR:
20497       {
20498 	vec<constructor_elt, va_gc> *n;
20499 	constructor_elt *ce;
20500 	unsigned HOST_WIDE_INT idx;
20501 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20502 	bool process_index_p;
20503         int newlen;
20504         bool need_copy_p = false;
20505 	tree r;
20506 
20507 	if (type == error_mark_node)
20508 	  RETURN (error_mark_node);
20509 
20510 	/* We do not want to process the index of aggregate
20511 	   initializers as they are identifier nodes which will be
20512 	   looked up by digest_init.  */
20513 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
20514 
20515 	if (null_member_pointer_value_p (t))
20516 	  {
20517 	    gcc_assert (same_type_p (type, TREE_TYPE (t)));
20518 	    RETURN (t);
20519 	  }
20520 
20521 	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
20522         newlen = vec_safe_length (n);
20523 	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
20524 	  {
20525 	    if (ce->index && process_index_p
20526 		/* An identifier index is looked up in the type
20527 		   being initialized, not the current scope.  */
20528 		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
20529 	      ce->index = RECUR (ce->index);
20530 
20531             if (PACK_EXPANSION_P (ce->value))
20532               {
20533                 /* Substitute into the pack expansion.  */
20534                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
20535                                                   in_decl);
20536 
20537 		if (ce->value == error_mark_node
20538 		    || PACK_EXPANSION_P (ce->value))
20539 		  ;
20540 		else if (TREE_VEC_LENGTH (ce->value) == 1)
20541                   /* Just move the argument into place.  */
20542                   ce->value = TREE_VEC_ELT (ce->value, 0);
20543                 else
20544                   {
20545                     /* Update the length of the final CONSTRUCTOR
20546                        arguments vector, and note that we will need to
20547                        copy.*/
20548                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
20549                     need_copy_p = true;
20550                   }
20551               }
20552             else
20553               ce->value = RECUR (ce->value);
20554 	  }
20555 
20556         if (need_copy_p)
20557           {
20558             vec<constructor_elt, va_gc> *old_n = n;
20559 
20560             vec_alloc (n, newlen);
20561             FOR_EACH_VEC_ELT (*old_n, idx, ce)
20562               {
20563                 if (TREE_CODE (ce->value) == TREE_VEC)
20564                   {
20565                     int i, len = TREE_VEC_LENGTH (ce->value);
20566                     for (i = 0; i < len; ++i)
20567                       CONSTRUCTOR_APPEND_ELT (n, 0,
20568                                               TREE_VEC_ELT (ce->value, i));
20569                   }
20570                 else
20571                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
20572               }
20573           }
20574 
20575 	r = build_constructor (init_list_type_node, n);
20576 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
20577 	CONSTRUCTOR_IS_DESIGNATED_INIT (r)
20578 	  = CONSTRUCTOR_IS_DESIGNATED_INIT (t);
20579 
20580 	if (TREE_HAS_CONSTRUCTOR (t))
20581 	  {
20582 	    fcl_t cl = fcl_functional;
20583 	    if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
20584 	      cl = fcl_c99;
20585 	    RETURN (finish_compound_literal (type, r, complain, cl));
20586 	  }
20587 
20588 	TREE_TYPE (r) = type;
20589 	RETURN (r);
20590       }
20591 
20592     case TYPEID_EXPR:
20593       {
20594 	tree operand_0 = TREE_OPERAND (t, 0);
20595 	if (TYPE_P (operand_0))
20596 	  {
20597 	    operand_0 = tsubst (operand_0, args, complain, in_decl);
20598 	    RETURN (get_typeid (operand_0, complain));
20599 	  }
20600 	else
20601 	  {
20602 	    operand_0 = RECUR (operand_0);
20603 	    RETURN (build_typeid (operand_0, complain));
20604 	  }
20605       }
20606 
20607     case VAR_DECL:
20608       if (!args)
20609 	RETURN (t);
20610       /* Fall through */
20611 
20612     case PARM_DECL:
20613       {
20614 	tree r = tsubst_copy (t, args, complain, in_decl);
20615 	/* ??? We're doing a subset of finish_id_expression here.  */
20616 	if (tree wrap = maybe_get_tls_wrapper_call (r))
20617 	  /* Replace an evaluated use of the thread_local variable with
20618 	     a call to its wrapper.  */
20619 	  r = wrap;
20620 	else if (outer_automatic_var_p (r))
20621 	  r = process_outer_var_ref (r, complain);
20622 
20623 	if (!TYPE_REF_P (TREE_TYPE (t)))
20624 	  /* If the original type was a reference, we'll be wrapped in
20625 	     the appropriate INDIRECT_REF.  */
20626 	  r = convert_from_reference (r);
20627 	RETURN (r);
20628       }
20629 
20630     case VA_ARG_EXPR:
20631       {
20632 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20633 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
20634 	RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
20635       }
20636 
20637     case OFFSETOF_EXPR:
20638       {
20639 	tree object_ptr
20640 	  = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
20641 				   in_decl, /*function_p=*/false,
20642 				   /*integral_constant_expression_p=*/false);
20643 	RETURN (finish_offsetof (object_ptr,
20644 				 RECUR (TREE_OPERAND (t, 0)),
20645 				 EXPR_LOCATION (t)));
20646       }
20647 
20648     case ADDRESSOF_EXPR:
20649       RETURN (cp_build_addressof (EXPR_LOCATION (t),
20650 				  RECUR (TREE_OPERAND (t, 0)), complain));
20651 
20652     case TRAIT_EXPR:
20653       {
20654 	tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
20655 			     complain, in_decl);
20656 	tree type2 = tsubst (TRAIT_EXPR_TYPE2 (t), args,
20657 			     complain, in_decl);
20658 	RETURN (finish_trait_expr (TRAIT_EXPR_LOCATION (t),
20659 				   TRAIT_EXPR_KIND (t), type1, type2));
20660       }
20661 
20662     case STMT_EXPR:
20663       {
20664 	tree old_stmt_expr = cur_stmt_expr;
20665 	tree stmt_expr = begin_stmt_expr ();
20666 
20667 	cur_stmt_expr = stmt_expr;
20668 	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
20669 		     integral_constant_expression_p);
20670 	stmt_expr = finish_stmt_expr (stmt_expr, false);
20671 	cur_stmt_expr = old_stmt_expr;
20672 
20673 	/* If the resulting list of expression statement is empty,
20674 	   fold it further into void_node.  */
20675 	if (empty_expr_stmt_p (stmt_expr))
20676 	  stmt_expr = void_node;
20677 
20678 	RETURN (stmt_expr);
20679       }
20680 
20681     case LAMBDA_EXPR:
20682       {
20683 	if (complain & tf_partial)
20684 	  {
20685 	    /* We don't have a full set of template arguments yet; don't touch
20686 	       the lambda at all.  */
20687 	    gcc_assert (processing_template_decl);
20688 	    return t;
20689 	  }
20690 	tree r = tsubst_lambda_expr (t, args, complain, in_decl);
20691 
20692 	RETURN (build_lambda_object (r));
20693       }
20694 
20695     case TARGET_EXPR:
20696       /* We can get here for a constant initializer of non-dependent type.
20697          FIXME stop folding in cp_parser_initializer_clause.  */
20698       {
20699 	tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
20700 					 complain);
20701 	RETURN (r);
20702       }
20703 
20704     case TRANSACTION_EXPR:
20705       RETURN (tsubst_expr(t, args, complain, in_decl,
20706 	     integral_constant_expression_p));
20707 
20708     case PAREN_EXPR:
20709       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
20710 
20711     case VEC_PERM_EXPR:
20712       {
20713 	tree op0 = RECUR (TREE_OPERAND (t, 0));
20714 	tree op1 = RECUR (TREE_OPERAND (t, 1));
20715 	tree op2 = RECUR (TREE_OPERAND (t, 2));
20716 	RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
20717 				       complain));
20718       }
20719 
20720     case REQUIRES_EXPR:
20721       {
20722 	tree r = tsubst_requires_expr (t, args, tf_none, in_decl);
20723 	RETURN (r);
20724       }
20725 
20726     case RANGE_EXPR:
20727       /* No need to substitute further, a RANGE_EXPR will always be built
20728 	 with constant operands.  */
20729       RETURN (t);
20730 
20731     case NON_LVALUE_EXPR:
20732     case VIEW_CONVERT_EXPR:
20733       if (location_wrapper_p (t))
20734 	/* We need to do this here as well as in tsubst_copy so we get the
20735 	   other tsubst_copy_and_build semantics for a PARM_DECL operand.  */
20736 	RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
20737 					  EXPR_LOCATION (t)));
20738       /* fallthrough.  */
20739 
20740     default:
20741       /* Handle Objective-C++ constructs, if appropriate.  */
20742       {
20743 	tree subst
20744 	  = objcp_tsubst_copy_and_build (t, args, complain,
20745 					 in_decl, /*function_p=*/false);
20746 	if (subst)
20747 	  RETURN (subst);
20748       }
20749       RETURN (tsubst_copy (t, args, complain, in_decl));
20750     }
20751 
20752 #undef RECUR
20753 #undef RETURN
20754  out:
20755   input_location = save_loc;
20756   return retval;
20757 }
20758 
20759 /* Verify that the instantiated ARGS are valid. For type arguments,
20760    make sure that the type's linkage is ok. For non-type arguments,
20761    make sure they are constants if they are integral or enumerations.
20762    Emit an error under control of COMPLAIN, and return TRUE on error.  */
20763 
20764 static bool
check_instantiated_arg(tree tmpl,tree t,tsubst_flags_t complain)20765 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
20766 {
20767   if (dependent_template_arg_p (t))
20768     return false;
20769   if (ARGUMENT_PACK_P (t))
20770     {
20771       tree vec = ARGUMENT_PACK_ARGS (t);
20772       int len = TREE_VEC_LENGTH (vec);
20773       bool result = false;
20774       int i;
20775 
20776       for (i = 0; i < len; ++i)
20777 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
20778 	  result = true;
20779       return result;
20780     }
20781   else if (TYPE_P (t))
20782     {
20783       /* [basic.link]: A name with no linkage (notably, the name
20784 	 of a class or enumeration declared in a local scope)
20785 	 shall not be used to declare an entity with linkage.
20786 	 This implies that names with no linkage cannot be used as
20787 	 template arguments
20788 
20789 	 DR 757 relaxes this restriction for C++0x.  */
20790       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
20791 		 : no_linkage_check (t, /*relaxed_p=*/false));
20792 
20793       if (nt)
20794 	{
20795 	  /* DR 488 makes use of a type with no linkage cause
20796 	     type deduction to fail.  */
20797 	  if (complain & tf_error)
20798 	    {
20799 	      if (TYPE_UNNAMED_P (nt))
20800 		error ("%qT is/uses unnamed type", t);
20801 	      else
20802 		error ("template argument for %qD uses local type %qT",
20803 		       tmpl, t);
20804 	    }
20805 	  return true;
20806 	}
20807       /* In order to avoid all sorts of complications, we do not
20808 	 allow variably-modified types as template arguments.  */
20809       else if (variably_modified_type_p (t, NULL_TREE))
20810 	{
20811 	  if (complain & tf_error)
20812 	    error ("%qT is a variably modified type", t);
20813 	  return true;
20814 	}
20815     }
20816   /* Class template and alias template arguments should be OK.  */
20817   else if (DECL_TYPE_TEMPLATE_P (t))
20818     ;
20819   /* A non-type argument of integral or enumerated type must be a
20820      constant.  */
20821   else if (TREE_TYPE (t)
20822 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
20823 	   && !REFERENCE_REF_P (t)
20824 	   && !TREE_CONSTANT (t))
20825     {
20826       if (complain & tf_error)
20827 	error ("integral expression %qE is not constant", t);
20828       return true;
20829     }
20830   return false;
20831 }
20832 
20833 static bool
check_instantiated_args(tree tmpl,tree args,tsubst_flags_t complain)20834 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
20835 {
20836   int ix, len = DECL_NTPARMS (tmpl);
20837   bool result = false;
20838 
20839   for (ix = 0; ix != len; ix++)
20840     {
20841       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
20842 	result = true;
20843     }
20844   if (result && (complain & tf_error))
20845     error ("  trying to instantiate %qD", tmpl);
20846   return result;
20847 }
20848 
20849 /* We're out of SFINAE context now, so generate diagnostics for the access
20850    errors we saw earlier when instantiating D from TMPL and ARGS.  */
20851 
20852 static void
recheck_decl_substitution(tree d,tree tmpl,tree args)20853 recheck_decl_substitution (tree d, tree tmpl, tree args)
20854 {
20855   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
20856   tree type = TREE_TYPE (pattern);
20857   location_t loc = input_location;
20858 
20859   push_access_scope (d);
20860   push_deferring_access_checks (dk_no_deferred);
20861   input_location = DECL_SOURCE_LOCATION (pattern);
20862   tsubst (type, args, tf_warning_or_error, d);
20863   input_location = loc;
20864   pop_deferring_access_checks ();
20865   pop_access_scope (d);
20866 }
20867 
20868 /* Instantiate the indicated variable, function, or alias template TMPL with
20869    the template arguments in TARG_PTR.  */
20870 
20871 static tree
instantiate_template_1(tree tmpl,tree orig_args,tsubst_flags_t complain)20872 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
20873 {
20874   tree targ_ptr = orig_args;
20875   tree fndecl;
20876   tree gen_tmpl;
20877   tree spec;
20878   bool access_ok = true;
20879 
20880   if (tmpl == error_mark_node)
20881     return error_mark_node;
20882 
20883   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
20884 
20885   /* If this function is a clone, handle it specially.  */
20886   if (DECL_CLONED_FUNCTION_P (tmpl))
20887     {
20888       tree spec;
20889       tree clone;
20890 
20891       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
20892 	 DECL_CLONED_FUNCTION.  */
20893       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
20894 				   targ_ptr, complain);
20895       if (spec == error_mark_node)
20896 	return error_mark_node;
20897 
20898       /* Look for the clone.  */
20899       FOR_EACH_CLONE (clone, spec)
20900 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
20901 	  return clone;
20902       /* We should always have found the clone by now.  */
20903       gcc_unreachable ();
20904       return NULL_TREE;
20905     }
20906 
20907   if (targ_ptr == error_mark_node)
20908     return error_mark_node;
20909 
20910   /* Check to see if we already have this specialization.  */
20911   gen_tmpl = most_general_template (tmpl);
20912   if (TMPL_ARGS_DEPTH (targ_ptr)
20913       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
20914     /* targ_ptr only has the innermost template args, so add the outer ones
20915        from tmpl, which could be either a partial instantiation or gen_tmpl (in
20916        the case of a non-dependent call within a template definition).  */
20917     targ_ptr = (add_outermost_template_args
20918 		(DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
20919 		 targ_ptr));
20920 
20921   /* It would be nice to avoid hashing here and then again in tsubst_decl,
20922      but it doesn't seem to be on the hot path.  */
20923   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
20924 
20925   gcc_assert (tmpl == gen_tmpl
20926 	      || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
20927 		  == spec)
20928 	      || fndecl == NULL_TREE);
20929 
20930   if (spec != NULL_TREE)
20931     {
20932       if (FNDECL_HAS_ACCESS_ERRORS (spec))
20933 	{
20934 	  if (complain & tf_error)
20935 	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
20936 	  return error_mark_node;
20937 	}
20938       return spec;
20939     }
20940 
20941   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
20942 			       complain))
20943     return error_mark_node;
20944 
20945   /* We are building a FUNCTION_DECL, during which the access of its
20946      parameters and return types have to be checked.  However this
20947      FUNCTION_DECL which is the desired context for access checking
20948      is not built yet.  We solve this chicken-and-egg problem by
20949      deferring all checks until we have the FUNCTION_DECL.  */
20950   push_deferring_access_checks (dk_deferred);
20951 
20952   /* Instantiation of the function happens in the context of the function
20953      template, not the context of the overload resolution we're doing.  */
20954   push_to_top_level ();
20955   /* If there are dependent arguments, e.g. because we're doing partial
20956      ordering, make sure processing_template_decl stays set.  */
20957   if (uses_template_parms (targ_ptr))
20958     ++processing_template_decl;
20959   if (DECL_CLASS_SCOPE_P (gen_tmpl))
20960     {
20961       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
20962 				   complain, gen_tmpl, true);
20963       push_nested_class (ctx);
20964     }
20965 
20966   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
20967 
20968   fndecl = NULL_TREE;
20969   if (VAR_P (pattern))
20970     {
20971       /* We need to determine if we're using a partial or explicit
20972 	 specialization now, because the type of the variable could be
20973 	 different.  */
20974       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
20975       tree elt = most_specialized_partial_spec (tid, complain);
20976       if (elt == error_mark_node)
20977 	pattern = error_mark_node;
20978       else if (elt)
20979 	{
20980 	  tree partial_tmpl = TREE_VALUE (elt);
20981 	  tree partial_args = TREE_PURPOSE (elt);
20982 	  tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
20983 	  fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
20984 	}
20985     }
20986 
20987   /* Substitute template parameters to obtain the specialization.  */
20988   if (fndecl == NULL_TREE)
20989     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
20990   if (DECL_CLASS_SCOPE_P (gen_tmpl))
20991     pop_nested_class ();
20992   pop_from_top_level ();
20993 
20994   if (fndecl == error_mark_node)
20995     {
20996       pop_deferring_access_checks ();
20997       return error_mark_node;
20998     }
20999 
21000   /* The DECL_TI_TEMPLATE should always be the immediate parent
21001      template, not the most general template.  */
21002   DECL_TI_TEMPLATE (fndecl) = tmpl;
21003   DECL_TI_ARGS (fndecl) = targ_ptr;
21004 
21005   /* Now we know the specialization, compute access previously
21006      deferred.  Do no access control for inheriting constructors,
21007      as we already checked access for the inherited constructor.  */
21008   if (!(flag_new_inheriting_ctors
21009 	&& DECL_INHERITED_CTOR (fndecl)))
21010     {
21011       push_access_scope (fndecl);
21012       if (!perform_deferred_access_checks (complain))
21013 	access_ok = false;
21014       pop_access_scope (fndecl);
21015     }
21016   pop_deferring_access_checks ();
21017 
21018   /* If we've just instantiated the main entry point for a function,
21019      instantiate all the alternate entry points as well.  We do this
21020      by cloning the instantiation of the main entry point, not by
21021      instantiating the template clones.  */
21022   if (tree chain = DECL_CHAIN (gen_tmpl))
21023     if (DECL_P (chain) && DECL_CLONED_FUNCTION_P (chain))
21024       clone_function_decl (fndecl, /*update_methods=*/false);
21025 
21026   if (!access_ok)
21027     {
21028       if (!(complain & tf_error))
21029 	{
21030 	  /* Remember to reinstantiate when we're out of SFINAE so the user
21031 	     can see the errors.  */
21032 	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
21033 	}
21034       return error_mark_node;
21035     }
21036   return fndecl;
21037 }
21038 
21039 /* Wrapper for instantiate_template_1.  */
21040 
21041 tree
instantiate_template(tree tmpl,tree orig_args,tsubst_flags_t complain)21042 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
21043 {
21044   tree ret;
21045   timevar_push (TV_TEMPLATE_INST);
21046   ret = instantiate_template_1 (tmpl, orig_args,  complain);
21047   timevar_pop (TV_TEMPLATE_INST);
21048   return ret;
21049 }
21050 
21051 /* Instantiate the alias template TMPL with ARGS.  Also push a template
21052    instantiation level, which instantiate_template doesn't do because
21053    functions and variables have sufficient context established by the
21054    callers.  */
21055 
21056 static tree
instantiate_alias_template(tree tmpl,tree args,tsubst_flags_t complain)21057 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
21058 {
21059   if (tmpl == error_mark_node || args == error_mark_node)
21060     return error_mark_node;
21061 
21062   args =
21063     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
21064 				     args, tmpl, complain,
21065 				     /*require_all_args=*/true,
21066 				     /*use_default_args=*/true);
21067 
21068   /* FIXME check for satisfaction in check_instantiated_args.  */
21069   if (flag_concepts
21070       && !any_dependent_template_arguments_p (args)
21071       && !constraints_satisfied_p (tmpl, args))
21072     {
21073       if (complain & tf_error)
21074 	{
21075 	  auto_diagnostic_group d;
21076 	  error ("template constraint failure for %qD", tmpl);
21077 	  diagnose_constraints (input_location, tmpl, args);
21078 	}
21079       return error_mark_node;
21080     }
21081 
21082   if (!push_tinst_level (tmpl, args))
21083     return error_mark_node;
21084   tree r = instantiate_template (tmpl, args, complain);
21085   pop_tinst_level ();
21086 
21087   return r;
21088 }
21089 
21090 /* PARM is a template parameter pack for FN.  Returns true iff
21091    PARM is used in a deducible way in the argument list of FN.  */
21092 
21093 static bool
pack_deducible_p(tree parm,tree fn)21094 pack_deducible_p (tree parm, tree fn)
21095 {
21096   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
21097   for (; t; t = TREE_CHAIN (t))
21098     {
21099       tree type = TREE_VALUE (t);
21100       tree packs;
21101       if (!PACK_EXPANSION_P (type))
21102 	continue;
21103       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
21104 	   packs; packs = TREE_CHAIN (packs))
21105 	if (template_args_equal (TREE_VALUE (packs), parm))
21106 	  {
21107 	    /* The template parameter pack is used in a function parameter
21108 	       pack.  If this is the end of the parameter list, the
21109 	       template parameter pack is deducible.  */
21110 	    if (TREE_CHAIN (t) == void_list_node)
21111 	      return true;
21112 	    else
21113 	      /* Otherwise, not.  Well, it could be deduced from
21114 		 a non-pack parameter, but doing so would end up with
21115 		 a deduction mismatch, so don't bother.  */
21116 	      return false;
21117 	  }
21118     }
21119   /* The template parameter pack isn't used in any function parameter
21120      packs, but it might be used deeper, e.g. tuple<Args...>.  */
21121   return true;
21122 }
21123 
21124 /* Subroutine of fn_type_unification: check non-dependent parms for
21125    convertibility.  */
21126 
21127 static int
check_non_deducible_conversions(tree parms,const tree * args,unsigned nargs,tree fn,unification_kind_t strict,int flags,struct conversion ** convs,bool explain_p)21128 check_non_deducible_conversions (tree parms, const tree *args, unsigned nargs,
21129 				 tree fn, unification_kind_t strict, int flags,
21130 				 struct conversion **convs, bool explain_p)
21131 {
21132   /* Non-constructor methods need to leave a conversion for 'this', which
21133      isn't included in nargs here.  */
21134   unsigned offset = (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
21135 		     && !DECL_CONSTRUCTOR_P (fn));
21136 
21137   for (unsigned ia = 0;
21138        parms && parms != void_list_node && ia < nargs; )
21139     {
21140       tree parm = TREE_VALUE (parms);
21141 
21142       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
21143 	  && (!TREE_CHAIN (parms)
21144 	      || TREE_CHAIN (parms) == void_list_node))
21145 	/* For a function parameter pack that occurs at the end of the
21146 	   parameter-declaration-list, the type A of each remaining
21147 	   argument of the call is compared with the type P of the
21148 	   declarator-id of the function parameter pack.  */
21149 	break;
21150 
21151       parms = TREE_CHAIN (parms);
21152 
21153       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
21154 	/* For a function parameter pack that does not occur at the
21155 	   end of the parameter-declaration-list, the type of the
21156 	   parameter pack is a non-deduced context.  */
21157 	continue;
21158 
21159       if (!uses_template_parms (parm))
21160 	{
21161 	  tree arg = args[ia];
21162 	  conversion **conv_p = convs ? &convs[ia+offset] : NULL;
21163 	  int lflags = conv_flags (ia, nargs, fn, arg, flags);
21164 
21165 	  if (check_non_deducible_conversion (parm, arg, strict, lflags,
21166 					      conv_p, explain_p))
21167 	    return 1;
21168 	}
21169 
21170       ++ia;
21171     }
21172 
21173   return 0;
21174 }
21175 
21176 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
21177    NARGS elements of the arguments that are being used when calling
21178    it.  TARGS is a vector into which the deduced template arguments
21179    are placed.
21180 
21181    Returns either a FUNCTION_DECL for the matching specialization of FN or
21182    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
21183    true, diagnostics will be printed to explain why it failed.
21184 
21185    If FN is a conversion operator, or we are trying to produce a specific
21186    specialization, RETURN_TYPE is the return type desired.
21187 
21188    The EXPLICIT_TARGS are explicit template arguments provided via a
21189    template-id.
21190 
21191    The parameter STRICT is one of:
21192 
21193    DEDUCE_CALL:
21194      We are deducing arguments for a function call, as in
21195      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
21196      deducing arguments for a call to the result of a conversion
21197      function template, as in [over.call.object].
21198 
21199    DEDUCE_CONV:
21200      We are deducing arguments for a conversion function, as in
21201      [temp.deduct.conv].
21202 
21203    DEDUCE_EXACT:
21204      We are deducing arguments when doing an explicit instantiation
21205      as in [temp.explicit], when determining an explicit specialization
21206      as in [temp.expl.spec], or when taking the address of a function
21207      template, as in [temp.deduct.funcaddr].  */
21208 
21209 tree
fn_type_unification(tree fn,tree explicit_targs,tree targs,const tree * args,unsigned int nargs,tree return_type,unification_kind_t strict,int flags,struct conversion ** convs,bool explain_p,bool decltype_p)21210 fn_type_unification (tree fn,
21211 		     tree explicit_targs,
21212 		     tree targs,
21213 		     const tree *args,
21214 		     unsigned int nargs,
21215 		     tree return_type,
21216 		     unification_kind_t strict,
21217 		     int flags,
21218 		     struct conversion **convs,
21219 		     bool explain_p,
21220 		     bool decltype_p)
21221 {
21222   tree parms;
21223   tree fntype;
21224   tree decl = NULL_TREE;
21225   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
21226   bool ok;
21227   static int deduction_depth;
21228   /* type_unification_real will pass back any access checks from default
21229      template argument substitution.  */
21230   vec<deferred_access_check, va_gc> *checks = NULL;
21231   /* We don't have all the template args yet.  */
21232   bool incomplete = true;
21233 
21234   tree orig_fn = fn;
21235   if (flag_new_inheriting_ctors)
21236     fn = strip_inheriting_ctors (fn);
21237 
21238   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
21239   tree r = error_mark_node;
21240 
21241   tree full_targs = targs;
21242   if (TMPL_ARGS_DEPTH (targs)
21243       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
21244     full_targs = (add_outermost_template_args
21245 		  (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
21246 		   targs));
21247 
21248   if (decltype_p)
21249     complain |= tf_decltype;
21250 
21251   /* In C++0x, it's possible to have a function template whose type depends
21252      on itself recursively.  This is most obvious with decltype, but can also
21253      occur with enumeration scope (c++/48969).  So we need to catch infinite
21254      recursion and reject the substitution at deduction time; this function
21255      will return error_mark_node for any repeated substitution.
21256 
21257      This also catches excessive recursion such as when f<N> depends on
21258      f<N-1> across all integers, and returns error_mark_node for all the
21259      substitutions back up to the initial one.
21260 
21261      This is, of course, not reentrant.  */
21262   if (excessive_deduction_depth)
21263     return error_mark_node;
21264   ++deduction_depth;
21265 
21266   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
21267 
21268   fntype = TREE_TYPE (fn);
21269   if (explicit_targs)
21270     {
21271       /* [temp.deduct]
21272 
21273 	 The specified template arguments must match the template
21274 	 parameters in kind (i.e., type, nontype, template), and there
21275 	 must not be more arguments than there are parameters;
21276 	 otherwise type deduction fails.
21277 
21278 	 Nontype arguments must match the types of the corresponding
21279 	 nontype template parameters, or must be convertible to the
21280 	 types of the corresponding nontype parameters as specified in
21281 	 _temp.arg.nontype_, otherwise type deduction fails.
21282 
21283 	 All references in the function type of the function template
21284 	 to the corresponding template parameters are replaced by the
21285 	 specified template argument values.  If a substitution in a
21286 	 template parameter or in the function type of the function
21287 	 template results in an invalid type, type deduction fails.  */
21288       int i, len = TREE_VEC_LENGTH (tparms);
21289       location_t loc = input_location;
21290       incomplete = false;
21291 
21292       if (explicit_targs == error_mark_node)
21293 	goto fail;
21294 
21295       if (TMPL_ARGS_DEPTH (explicit_targs)
21296 	  < TMPL_ARGS_DEPTH (full_targs))
21297 	explicit_targs = add_outermost_template_args (full_targs,
21298 						      explicit_targs);
21299 
21300       /* Adjust any explicit template arguments before entering the
21301 	 substitution context.  */
21302       explicit_targs
21303 	= (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
21304 				  complain|tf_partial,
21305 				  /*require_all_args=*/false,
21306 				  /*use_default_args=*/false));
21307       if (explicit_targs == error_mark_node)
21308 	goto fail;
21309 
21310       /* Substitute the explicit args into the function type.  This is
21311 	 necessary so that, for instance, explicitly declared function
21312 	 arguments can match null pointed constants.  If we were given
21313 	 an incomplete set of explicit args, we must not do semantic
21314 	 processing during substitution as we could create partial
21315 	 instantiations.  */
21316       for (i = 0; i < len; i++)
21317         {
21318           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
21319           bool parameter_pack = false;
21320 	  tree targ = TREE_VEC_ELT (explicit_targs, i);
21321 
21322           /* Dig out the actual parm.  */
21323           if (TREE_CODE (parm) == TYPE_DECL
21324               || TREE_CODE (parm) == TEMPLATE_DECL)
21325             {
21326               parm = TREE_TYPE (parm);
21327               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
21328             }
21329           else if (TREE_CODE (parm) == PARM_DECL)
21330             {
21331               parm = DECL_INITIAL (parm);
21332               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
21333             }
21334 
21335 	  if (targ == NULL_TREE)
21336 	    /* No explicit argument for this template parameter.  */
21337 	    incomplete = true;
21338 	  else if (parameter_pack && pack_deducible_p (parm, fn))
21339             {
21340               /* Mark the argument pack as "incomplete". We could
21341                  still deduce more arguments during unification.
21342 	         We remove this mark in type_unification_real.  */
21343 	      ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
21344 	      ARGUMENT_PACK_EXPLICIT_ARGS (targ)
21345 		= ARGUMENT_PACK_ARGS (targ);
21346 
21347               /* We have some incomplete argument packs.  */
21348               incomplete = true;
21349             }
21350         }
21351 
21352       if (incomplete)
21353 	{
21354 	  if (!push_tinst_level (fn, explicit_targs))
21355 	    {
21356 	      excessive_deduction_depth = true;
21357 	      goto fail;
21358 	    }
21359 	  ++processing_template_decl;
21360 	  input_location = DECL_SOURCE_LOCATION (fn);
21361 	  /* Ignore any access checks; we'll see them again in
21362 	     instantiate_template and they might have the wrong
21363 	     access path at this point.  */
21364 	  push_deferring_access_checks (dk_deferred);
21365 	  tsubst_flags_t ecomplain = complain | tf_partial | tf_fndecl_type;
21366 	  fntype = tsubst (TREE_TYPE (fn), explicit_targs, ecomplain, NULL_TREE);
21367 	  pop_deferring_access_checks ();
21368 	  input_location = loc;
21369 	  --processing_template_decl;
21370 	  pop_tinst_level ();
21371 
21372 	  if (fntype == error_mark_node)
21373 	    goto fail;
21374 	}
21375 
21376       /* Place the explicitly specified arguments in TARGS.  */
21377       explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
21378       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
21379 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
21380       if (!incomplete && CHECKING_P
21381 	  && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
21382 	SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
21383 	  (targs, NUM_TMPL_ARGS (explicit_targs));
21384     }
21385 
21386   if (return_type && strict != DEDUCE_CALL)
21387     {
21388       tree *new_args = XALLOCAVEC (tree, nargs + 1);
21389       new_args[0] = return_type;
21390       memcpy (new_args + 1, args, nargs * sizeof (tree));
21391       args = new_args;
21392       ++nargs;
21393     }
21394 
21395   if (!incomplete)
21396     goto deduced;
21397 
21398   /* Never do unification on the 'this' parameter.  */
21399   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
21400 
21401   if (return_type && strict == DEDUCE_CALL)
21402     {
21403       /* We're deducing for a call to the result of a template conversion
21404          function.  The parms we really want are in return_type.  */
21405       if (INDIRECT_TYPE_P (return_type))
21406 	return_type = TREE_TYPE (return_type);
21407       parms = TYPE_ARG_TYPES (return_type);
21408     }
21409   else if (return_type)
21410     {
21411       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
21412     }
21413 
21414   /* We allow incomplete unification without an error message here
21415      because the standard doesn't seem to explicitly prohibit it.  Our
21416      callers must be ready to deal with unification failures in any
21417      event.  */
21418 
21419   /* If we aren't explaining yet, push tinst context so we can see where
21420      any errors (e.g. from class instantiations triggered by instantiation
21421      of default template arguments) come from.  If we are explaining, this
21422      context is redundant.  */
21423   if (!explain_p && !push_tinst_level (fn, targs))
21424     {
21425       excessive_deduction_depth = true;
21426       goto fail;
21427     }
21428 
21429   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
21430 			       full_targs, parms, args, nargs, /*subr=*/0,
21431 			       strict, &checks, explain_p);
21432   if (!explain_p)
21433     pop_tinst_level ();
21434   if (!ok)
21435     goto fail;
21436 
21437   /* Now that we have bindings for all of the template arguments,
21438      ensure that the arguments deduced for the template template
21439      parameters have compatible template parameter lists.  We cannot
21440      check this property before we have deduced all template
21441      arguments, because the template parameter types of a template
21442      template parameter might depend on prior template parameters
21443      deduced after the template template parameter.  The following
21444      ill-formed example illustrates this issue:
21445 
21446        template<typename T, template<T> class C> void f(C<5>, T);
21447 
21448        template<int N> struct X {};
21449 
21450        void g() {
21451          f(X<5>(), 5l); // error: template argument deduction fails
21452        }
21453 
21454      The template parameter list of 'C' depends on the template type
21455      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
21456      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
21457      time that we deduce 'C'.  */
21458   if (!template_template_parm_bindings_ok_p
21459            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
21460     {
21461       unify_inconsistent_template_template_parameters (explain_p);
21462       goto fail;
21463     }
21464 
21465   /* DR 1391: All parameters have args, now check non-dependent parms for
21466      convertibility.  */
21467   if (check_non_deducible_conversions (parms, args, nargs, fn, strict, flags,
21468 				       convs, explain_p))
21469     goto fail;
21470 
21471  deduced:
21472   /* All is well so far.  Now, check:
21473 
21474      [temp.deduct]
21475 
21476      When all template arguments have been deduced, all uses of
21477      template parameters in nondeduced contexts are replaced with
21478      the corresponding deduced argument values.  If the
21479      substitution results in an invalid type, as described above,
21480      type deduction fails.  */
21481   if (!push_tinst_level (fn, targs))
21482     {
21483       excessive_deduction_depth = true;
21484       goto fail;
21485     }
21486 
21487   /* Also collect access checks from the instantiation.  */
21488   reopen_deferring_access_checks (checks);
21489 
21490   decl = instantiate_template (fn, targs, complain);
21491 
21492   checks = get_deferred_access_checks ();
21493   pop_deferring_access_checks ();
21494 
21495   pop_tinst_level ();
21496 
21497   if (decl == error_mark_node)
21498     goto fail;
21499 
21500   /* Now perform any access checks encountered during substitution.  */
21501   push_access_scope (decl);
21502   ok = perform_access_checks (checks, complain);
21503   pop_access_scope (decl);
21504   if (!ok)
21505     goto fail;
21506 
21507   /* If we're looking for an exact match, check that what we got
21508      is indeed an exact match.  It might not be if some template
21509      parameters are used in non-deduced contexts.  But don't check
21510      for an exact match if we have dependent template arguments;
21511      in that case we're doing partial ordering, and we already know
21512      that we have two candidates that will provide the actual type.  */
21513   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
21514     {
21515       tree substed = TREE_TYPE (decl);
21516       unsigned int i;
21517 
21518       tree sarg
21519 	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
21520       if (return_type)
21521 	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
21522       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
21523 	if (!same_type_p (args[i], TREE_VALUE (sarg)))
21524 	  {
21525 	    unify_type_mismatch (explain_p, args[i],
21526 				 TREE_VALUE (sarg));
21527 	    goto fail;
21528 	  }
21529     }
21530 
21531   /* After doing deduction with the inherited constructor, actually return an
21532      instantiation of the inheriting constructor.  */
21533   if (orig_fn != fn)
21534     decl = instantiate_template (orig_fn, targs, complain);
21535 
21536   r = decl;
21537 
21538  fail:
21539   --deduction_depth;
21540   if (excessive_deduction_depth)
21541     {
21542       if (deduction_depth == 0)
21543 	/* Reset once we're all the way out.  */
21544 	excessive_deduction_depth = false;
21545     }
21546 
21547   return r;
21548 }
21549 
21550 /* Adjust types before performing type deduction, as described in
21551    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
21552    sections are symmetric.  PARM is the type of a function parameter
21553    or the return type of the conversion function.  ARG is the type of
21554    the argument passed to the call, or the type of the value
21555    initialized with the result of the conversion function.
21556    ARG_EXPR is the original argument expression, which may be null.  */
21557 
21558 static int
maybe_adjust_types_for_deduction(unification_kind_t strict,tree * parm,tree * arg,tree arg_expr)21559 maybe_adjust_types_for_deduction (unification_kind_t strict,
21560 				  tree* parm,
21561 				  tree* arg,
21562 				  tree arg_expr)
21563 {
21564   int result = 0;
21565 
21566   switch (strict)
21567     {
21568     case DEDUCE_CALL:
21569       break;
21570 
21571     case DEDUCE_CONV:
21572       /* Swap PARM and ARG throughout the remainder of this
21573 	 function; the handling is precisely symmetric since PARM
21574 	 will initialize ARG rather than vice versa.  */
21575       std::swap (parm, arg);
21576       break;
21577 
21578     case DEDUCE_EXACT:
21579       /* Core issue #873: Do the DR606 thing (see below) for these cases,
21580 	 too, but here handle it by stripping the reference from PARM
21581 	 rather than by adding it to ARG.  */
21582       if (TYPE_REF_P (*parm)
21583 	  && TYPE_REF_IS_RVALUE (*parm)
21584 	  && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
21585 	  && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
21586 	  && TYPE_REF_P (*arg)
21587 	  && !TYPE_REF_IS_RVALUE (*arg))
21588 	*parm = TREE_TYPE (*parm);
21589       /* Nothing else to do in this case.  */
21590       return 0;
21591 
21592     default:
21593       gcc_unreachable ();
21594     }
21595 
21596   if (!TYPE_REF_P (*parm))
21597     {
21598       /* [temp.deduct.call]
21599 
21600 	 If P is not a reference type:
21601 
21602 	 --If A is an array type, the pointer type produced by the
21603 	 array-to-pointer standard conversion (_conv.array_) is
21604 	 used in place of A for type deduction; otherwise,
21605 
21606 	 --If A is a function type, the pointer type produced by
21607 	 the function-to-pointer standard conversion
21608 	 (_conv.func_) is used in place of A for type deduction;
21609 	 otherwise,
21610 
21611 	 --If A is a cv-qualified type, the top level
21612 	 cv-qualifiers of A's type are ignored for type
21613 	 deduction.  */
21614       if (TREE_CODE (*arg) == ARRAY_TYPE)
21615 	*arg = build_pointer_type (TREE_TYPE (*arg));
21616       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
21617 	*arg = build_pointer_type (*arg);
21618       else
21619 	*arg = TYPE_MAIN_VARIANT (*arg);
21620     }
21621 
21622   /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
21623      reference to a cv-unqualified template parameter that does not represent a
21624      template parameter of a class template (during class template argument
21625      deduction (13.3.1.8)). If P is a forwarding reference and the argument is
21626      an lvalue, the type "lvalue reference to A" is used in place of A for type
21627      deduction. */
21628   if (TYPE_REF_P (*parm)
21629       && TYPE_REF_IS_RVALUE (*parm)
21630       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
21631       && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
21632       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
21633       && (arg_expr ? lvalue_p (arg_expr)
21634 	  /* try_one_overload doesn't provide an arg_expr, but
21635 	     functions are always lvalues.  */
21636 	  : TREE_CODE (*arg) == FUNCTION_TYPE))
21637     *arg = build_reference_type (*arg);
21638 
21639   /* [temp.deduct.call]
21640 
21641      If P is a cv-qualified type, the top level cv-qualifiers
21642      of P's type are ignored for type deduction.  If P is a
21643      reference type, the type referred to by P is used for
21644      type deduction.  */
21645   *parm = TYPE_MAIN_VARIANT (*parm);
21646   if (TYPE_REF_P (*parm))
21647     {
21648       *parm = TREE_TYPE (*parm);
21649       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
21650     }
21651 
21652   /* DR 322. For conversion deduction, remove a reference type on parm
21653      too (which has been swapped into ARG).  */
21654   if (strict == DEDUCE_CONV && TYPE_REF_P (*arg))
21655     *arg = TREE_TYPE (*arg);
21656 
21657   return result;
21658 }
21659 
21660 /* Subroutine of fn_type_unification.  PARM is a function parameter of a
21661    template which doesn't contain any deducible template parameters; check if
21662    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
21663    unify_one_argument.  */
21664 
21665 static int
check_non_deducible_conversion(tree parm,tree arg,int strict,int flags,struct conversion ** conv_p,bool explain_p)21666 check_non_deducible_conversion (tree parm, tree arg, int strict,
21667 				int flags, struct conversion **conv_p,
21668 				bool explain_p)
21669 {
21670   tree type;
21671 
21672   if (!TYPE_P (arg))
21673     type = TREE_TYPE (arg);
21674   else
21675     type = arg;
21676 
21677   if (same_type_p (parm, type))
21678     return unify_success (explain_p);
21679 
21680   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
21681   if (strict == DEDUCE_CONV)
21682     {
21683       if (can_convert_arg (type, parm, NULL_TREE, flags, complain))
21684 	return unify_success (explain_p);
21685     }
21686   else if (strict != DEDUCE_EXACT)
21687     {
21688       bool ok = false;
21689       tree conv_arg = TYPE_P (arg) ? NULL_TREE : arg;
21690       if (conv_p)
21691 	/* Avoid recalculating this in add_function_candidate.  */
21692 	ok = (*conv_p
21693 	      = good_conversion (parm, type, conv_arg, flags, complain));
21694       else
21695 	ok = can_convert_arg (parm, type, conv_arg, flags, complain);
21696       if (ok)
21697 	return unify_success (explain_p);
21698     }
21699 
21700   if (strict == DEDUCE_EXACT)
21701     return unify_type_mismatch (explain_p, parm, arg);
21702   else
21703     return unify_arg_conversion (explain_p, parm, type, arg);
21704 }
21705 
21706 static bool uses_deducible_template_parms (tree type);
21707 
21708 /* Returns true iff the expression EXPR is one from which a template
21709    argument can be deduced.  In other words, if it's an undecorated
21710    use of a template non-type parameter.  */
21711 
21712 static bool
deducible_expression(tree expr)21713 deducible_expression (tree expr)
21714 {
21715   /* Strip implicit conversions and implicit INDIRECT_REFs.  */
21716   while (CONVERT_EXPR_P (expr)
21717 	 || TREE_CODE (expr) == VIEW_CONVERT_EXPR
21718 	 || REFERENCE_REF_P (expr))
21719     expr = TREE_OPERAND (expr, 0);
21720   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
21721 }
21722 
21723 /* Returns true iff the array domain DOMAIN uses a template parameter in a
21724    deducible way; that is, if it has a max value of <PARM> - 1.  */
21725 
21726 static bool
deducible_array_bound(tree domain)21727 deducible_array_bound (tree domain)
21728 {
21729   if (domain == NULL_TREE)
21730     return false;
21731 
21732   tree max = TYPE_MAX_VALUE (domain);
21733   if (TREE_CODE (max) != MINUS_EXPR)
21734     return false;
21735 
21736   return deducible_expression (TREE_OPERAND (max, 0));
21737 }
21738 
21739 /* Returns true iff the template arguments ARGS use a template parameter
21740    in a deducible way.  */
21741 
21742 static bool
deducible_template_args(tree args)21743 deducible_template_args (tree args)
21744 {
21745   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
21746     {
21747       bool deducible;
21748       tree elt = TREE_VEC_ELT (args, i);
21749       if (ARGUMENT_PACK_P (elt))
21750 	deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
21751       else
21752 	{
21753 	  if (PACK_EXPANSION_P (elt))
21754 	    elt = PACK_EXPANSION_PATTERN (elt);
21755 	  if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
21756 	    deducible = true;
21757 	  else if (TYPE_P (elt))
21758 	    deducible = uses_deducible_template_parms (elt);
21759 	  else
21760 	    deducible = deducible_expression (elt);
21761 	}
21762       if (deducible)
21763 	return true;
21764     }
21765   return false;
21766 }
21767 
21768 /* Returns true iff TYPE contains any deducible references to template
21769    parameters, as per 14.8.2.5.  */
21770 
21771 static bool
uses_deducible_template_parms(tree type)21772 uses_deducible_template_parms (tree type)
21773 {
21774   if (PACK_EXPANSION_P (type))
21775     type = PACK_EXPANSION_PATTERN (type);
21776 
21777   /* T
21778      cv-list T
21779      TT<T>
21780      TT<i>
21781      TT<> */
21782   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
21783       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
21784     return true;
21785 
21786   /* T*
21787      T&
21788      T&&  */
21789   if (INDIRECT_TYPE_P (type))
21790     return uses_deducible_template_parms (TREE_TYPE (type));
21791 
21792   /* T[integer-constant ]
21793      type [i]  */
21794   if (TREE_CODE (type) == ARRAY_TYPE)
21795     return (uses_deducible_template_parms (TREE_TYPE (type))
21796 	    || deducible_array_bound (TYPE_DOMAIN (type)));
21797 
21798   /* T type ::*
21799      type T::*
21800      T T::*
21801      T (type ::*)()
21802      type (T::*)()
21803      type (type ::*)(T)
21804      type (T::*)(T)
21805      T (type ::*)(T)
21806      T (T::*)()
21807      T (T::*)(T) */
21808   if (TYPE_PTRMEM_P (type))
21809     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
21810 	    || (uses_deducible_template_parms
21811 		(TYPE_PTRMEM_POINTED_TO_TYPE (type))));
21812 
21813   /* template-name <T> (where template-name refers to a class template)
21814      template-name <i> (where template-name refers to a class template) */
21815   if (CLASS_TYPE_P (type)
21816       && CLASSTYPE_TEMPLATE_INFO (type)
21817       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
21818     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
21819 				    (CLASSTYPE_TI_ARGS (type)));
21820 
21821   /* type (T)
21822      T()
21823      T(T)  */
21824   if (FUNC_OR_METHOD_TYPE_P (type))
21825     {
21826       if (uses_deducible_template_parms (TREE_TYPE (type)))
21827 	return true;
21828       tree parm = TYPE_ARG_TYPES (type);
21829       if (TREE_CODE (type) == METHOD_TYPE)
21830 	parm = TREE_CHAIN (parm);
21831       for (; parm; parm = TREE_CHAIN (parm))
21832 	if (uses_deducible_template_parms (TREE_VALUE (parm)))
21833 	  return true;
21834     }
21835 
21836   return false;
21837 }
21838 
21839 /* Subroutine of type_unification_real and unify_pack_expansion to
21840    handle unification of a single P/A pair.  Parameters are as
21841    for those functions.  */
21842 
21843 static int
unify_one_argument(tree tparms,tree targs,tree parm,tree arg,int subr,unification_kind_t strict,bool explain_p)21844 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
21845 		    int subr, unification_kind_t strict,
21846 		    bool explain_p)
21847 {
21848   tree arg_expr = NULL_TREE;
21849   int arg_strict;
21850 
21851   if (arg == error_mark_node || parm == error_mark_node)
21852     return unify_invalid (explain_p);
21853   if (arg == unknown_type_node)
21854     /* We can't deduce anything from this, but we might get all the
21855        template args from other function args.  */
21856     return unify_success (explain_p);
21857 
21858   /* Implicit conversions (Clause 4) will be performed on a function
21859      argument to convert it to the type of the corresponding function
21860      parameter if the parameter type contains no template-parameters that
21861      participate in template argument deduction.  */
21862   if (strict != DEDUCE_EXACT
21863       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
21864     /* For function parameters with no deducible template parameters,
21865        just return.  We'll check non-dependent conversions later.  */
21866     return unify_success (explain_p);
21867 
21868   switch (strict)
21869     {
21870     case DEDUCE_CALL:
21871       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
21872 		    | UNIFY_ALLOW_MORE_CV_QUAL
21873 		    | UNIFY_ALLOW_DERIVED);
21874       break;
21875 
21876     case DEDUCE_CONV:
21877       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
21878       break;
21879 
21880     case DEDUCE_EXACT:
21881       arg_strict = UNIFY_ALLOW_NONE;
21882       break;
21883 
21884     default:
21885       gcc_unreachable ();
21886     }
21887 
21888   /* We only do these transformations if this is the top-level
21889      parameter_type_list in a call or declaration matching; in other
21890      situations (nested function declarators, template argument lists) we
21891      won't be comparing a type to an expression, and we don't do any type
21892      adjustments.  */
21893   if (!subr)
21894     {
21895       if (!TYPE_P (arg))
21896 	{
21897 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
21898 	  if (type_unknown_p (arg))
21899 	    {
21900 	      /* [temp.deduct.type] A template-argument can be
21901 		 deduced from a pointer to function or pointer
21902 		 to member function argument if the set of
21903 		 overloaded functions does not contain function
21904 		 templates and at most one of a set of
21905 		 overloaded functions provides a unique
21906 		 match.  */
21907 	      resolve_overloaded_unification (tparms, targs, parm,
21908 					      arg, strict,
21909 					      arg_strict, explain_p);
21910 	      /* If a unique match was not found, this is a
21911 	         non-deduced context, so we still succeed. */
21912 	      return unify_success (explain_p);
21913 	    }
21914 
21915 	  arg_expr = arg;
21916 	  arg = unlowered_expr_type (arg);
21917 	  if (arg == error_mark_node)
21918 	    return unify_invalid (explain_p);
21919 	}
21920 
21921       arg_strict |=
21922 	maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
21923     }
21924   else
21925     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
21926 	!= (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
21927       return unify_template_argument_mismatch (explain_p, parm, arg);
21928 
21929   /* For deduction from an init-list we need the actual list.  */
21930   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
21931     arg = arg_expr;
21932   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
21933 }
21934 
21935 /* for_each_template_parm callback that always returns 0.  */
21936 
21937 static int
zero_r(tree,void *)21938 zero_r (tree, void *)
21939 {
21940   return 0;
21941 }
21942 
21943 /* for_each_template_parm any_fn callback to handle deduction of a template
21944    type argument from the type of an array bound.  */
21945 
21946 static int
array_deduction_r(tree t,void * data)21947 array_deduction_r (tree t, void *data)
21948 {
21949   tree_pair_p d = (tree_pair_p)data;
21950   tree &tparms = d->purpose;
21951   tree &targs = d->value;
21952 
21953   if (TREE_CODE (t) == ARRAY_TYPE)
21954     if (tree dom = TYPE_DOMAIN (t))
21955       if (tree max = TYPE_MAX_VALUE (dom))
21956 	{
21957 	  if (TREE_CODE (max) == MINUS_EXPR)
21958 	    max = TREE_OPERAND (max, 0);
21959 	  if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
21960 	    unify (tparms, targs, TREE_TYPE (max), size_type_node,
21961 		   UNIFY_ALLOW_NONE, /*explain*/false);
21962 	}
21963 
21964   /* Keep walking.  */
21965   return 0;
21966 }
21967 
21968 /* Try to deduce any not-yet-deduced template type arguments from the type of
21969    an array bound.  This is handled separately from unify because 14.8.2.5 says
21970    "The type of a type parameter is only deduced from an array bound if it is
21971    not otherwise deduced."  */
21972 
21973 static void
try_array_deduction(tree tparms,tree targs,tree parm)21974 try_array_deduction (tree tparms, tree targs, tree parm)
21975 {
21976   tree_pair_s data = { tparms, targs };
21977   hash_set<tree> visited;
21978   for_each_template_parm (parm, zero_r, &data, &visited,
21979 			  /*nondeduced*/false, array_deduction_r);
21980 }
21981 
21982 /* Most parms like fn_type_unification.
21983 
21984    If SUBR is 1, we're being called recursively (to unify the
21985    arguments of a function or method parameter of a function
21986    template).
21987 
21988    CHECKS is a pointer to a vector of access checks encountered while
21989    substituting default template arguments.  */
21990 
21991 static int
type_unification_real(tree tparms,tree full_targs,tree xparms,const tree * xargs,unsigned int xnargs,int subr,unification_kind_t strict,vec<deferred_access_check,va_gc> ** checks,bool explain_p)21992 type_unification_real (tree tparms,
21993 		       tree full_targs,
21994 		       tree xparms,
21995 		       const tree *xargs,
21996 		       unsigned int xnargs,
21997 		       int subr,
21998 		       unification_kind_t strict,
21999 		       vec<deferred_access_check, va_gc> **checks,
22000 		       bool explain_p)
22001 {
22002   tree parm, arg;
22003   int i;
22004   int ntparms = TREE_VEC_LENGTH (tparms);
22005   int saw_undeduced = 0;
22006   tree parms;
22007   const tree *args;
22008   unsigned int nargs;
22009   unsigned int ia;
22010 
22011   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
22012   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
22013   gcc_assert (ntparms > 0);
22014 
22015   tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
22016 
22017   /* Reset the number of non-defaulted template arguments contained
22018      in TARGS.  */
22019   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
22020 
22021  again:
22022   parms = xparms;
22023   args = xargs;
22024   nargs = xnargs;
22025 
22026   ia = 0;
22027   while (parms && parms != void_list_node
22028 	 && ia < nargs)
22029     {
22030       parm = TREE_VALUE (parms);
22031 
22032       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
22033 	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
22034 	/* For a function parameter pack that occurs at the end of the
22035 	   parameter-declaration-list, the type A of each remaining
22036 	   argument of the call is compared with the type P of the
22037 	   declarator-id of the function parameter pack.  */
22038 	break;
22039 
22040       parms = TREE_CHAIN (parms);
22041 
22042       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
22043 	/* For a function parameter pack that does not occur at the
22044 	   end of the parameter-declaration-list, the type of the
22045 	   parameter pack is a non-deduced context.  */
22046 	continue;
22047 
22048       arg = args[ia];
22049       ++ia;
22050 
22051       if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
22052 			      explain_p))
22053 	return 1;
22054     }
22055 
22056   if (parms
22057       && parms != void_list_node
22058       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
22059     {
22060       /* Unify the remaining arguments with the pack expansion type.  */
22061       tree argvec;
22062       tree parmvec = make_tree_vec (1);
22063 
22064       /* Allocate a TREE_VEC and copy in all of the arguments */
22065       argvec = make_tree_vec (nargs - ia);
22066       for (i = 0; ia < nargs; ++ia, ++i)
22067 	TREE_VEC_ELT (argvec, i) = args[ia];
22068 
22069       /* Copy the parameter into parmvec.  */
22070       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
22071       if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
22072                                 /*subr=*/subr, explain_p))
22073         return 1;
22074 
22075       /* Advance to the end of the list of parameters.  */
22076       parms = TREE_CHAIN (parms);
22077     }
22078 
22079   /* Fail if we've reached the end of the parm list, and more args
22080      are present, and the parm list isn't variadic.  */
22081   if (ia < nargs && parms == void_list_node)
22082     return unify_too_many_arguments (explain_p, nargs, ia);
22083   /* Fail if parms are left and they don't have default values and
22084      they aren't all deduced as empty packs (c++/57397).  This is
22085      consistent with sufficient_parms_p.  */
22086   if (parms && parms != void_list_node
22087       && TREE_PURPOSE (parms) == NULL_TREE)
22088     {
22089       unsigned int count = nargs;
22090       tree p = parms;
22091       bool type_pack_p;
22092       do
22093 	{
22094 	  type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
22095 	  if (!type_pack_p)
22096 	    count++;
22097 	  p = TREE_CHAIN (p);
22098 	}
22099       while (p && p != void_list_node);
22100       if (count != nargs)
22101 	return unify_too_few_arguments (explain_p, ia, count,
22102 					type_pack_p);
22103     }
22104 
22105   if (!subr)
22106     {
22107       tsubst_flags_t complain = (explain_p
22108 				 ? tf_warning_or_error
22109 				 : tf_none);
22110       bool tried_array_deduction = (cxx_dialect < cxx17);
22111 
22112       for (i = 0; i < ntparms; i++)
22113 	{
22114 	  tree targ = TREE_VEC_ELT (targs, i);
22115 	  tree tparm = TREE_VEC_ELT (tparms, i);
22116 
22117 	  /* Clear the "incomplete" flags on all argument packs now so that
22118 	     substituting them into later default arguments works.  */
22119 	  if (targ && ARGUMENT_PACK_P (targ))
22120             {
22121               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
22122               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
22123             }
22124 
22125 	  if (targ || tparm == error_mark_node)
22126 	    continue;
22127 	  tparm = TREE_VALUE (tparm);
22128 
22129 	  if (TREE_CODE (tparm) == TYPE_DECL
22130 	      && !tried_array_deduction)
22131 	    {
22132 	      try_array_deduction (tparms, targs, xparms);
22133 	      tried_array_deduction = true;
22134 	      if (TREE_VEC_ELT (targs, i))
22135 		continue;
22136 	    }
22137 
22138 	  /* If this is an undeduced nontype parameter that depends on
22139 	     a type parameter, try another pass; its type may have been
22140 	     deduced from a later argument than the one from which
22141 	     this parameter can be deduced.  */
22142 	  if (TREE_CODE (tparm) == PARM_DECL
22143 	      && uses_template_parms (TREE_TYPE (tparm))
22144 	      && saw_undeduced < 2)
22145 	    {
22146 	      saw_undeduced = 1;
22147 	      continue;
22148 	    }
22149 
22150 	  /* Core issue #226 (C++0x) [temp.deduct]:
22151 
22152 	     If a template argument has not been deduced, its
22153 	     default template argument, if any, is used.
22154 
22155 	     When we are in C++98 mode, TREE_PURPOSE will either
22156 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
22157 	     to explicitly check cxx_dialect here.  */
22158 	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
22159 	    /* OK, there is a default argument.  Wait until after the
22160 	       conversion check to do substitution.  */
22161 	    continue;
22162 
22163 	  /* If the type parameter is a parameter pack, then it will
22164 	     be deduced to an empty parameter pack.  */
22165 	  if (template_parameter_pack_p (tparm))
22166 	    {
22167 	      tree arg;
22168 
22169 	      if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
22170 		{
22171 		  arg = make_node (NONTYPE_ARGUMENT_PACK);
22172 		  TREE_CONSTANT (arg) = 1;
22173 		}
22174 	      else
22175 		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
22176 
22177 	      SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
22178 
22179 	      TREE_VEC_ELT (targs, i) = arg;
22180 	      continue;
22181 	    }
22182 
22183 	  return unify_parameter_deduction_failure (explain_p, tparm);
22184 	}
22185 
22186       /* Now substitute into the default template arguments.  */
22187       for (i = 0; i < ntparms; i++)
22188 	{
22189 	  tree targ = TREE_VEC_ELT (targs, i);
22190 	  tree tparm = TREE_VEC_ELT (tparms, i);
22191 
22192 	  if (targ || tparm == error_mark_node)
22193 	    continue;
22194 	  tree parm = TREE_VALUE (tparm);
22195 	  tree arg = TREE_PURPOSE (tparm);
22196 	  reopen_deferring_access_checks (*checks);
22197 	  location_t save_loc = input_location;
22198 	  if (DECL_P (parm))
22199 	    input_location = DECL_SOURCE_LOCATION (parm);
22200 
22201 	  if (saw_undeduced == 1
22202 	      && TREE_CODE (parm) == PARM_DECL
22203 	      && uses_template_parms (TREE_TYPE (parm)))
22204 	    {
22205 	      /* The type of this non-type parameter depends on undeduced
22206 		 parameters.  Don't try to use its default argument yet,
22207 		 since we might deduce an argument for it on the next pass,
22208 		 but do check whether the arguments we already have cause
22209 		 substitution failure, so that that happens before we try
22210 		 later default arguments (78489).  */
22211 	      ++processing_template_decl;
22212 	      tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
22213 				  NULL_TREE);
22214 	      --processing_template_decl;
22215 	      if (type == error_mark_node)
22216 		arg = error_mark_node;
22217 	      else
22218 		arg = NULL_TREE;
22219 	    }
22220 	  else
22221 	    {
22222 	      /* Even if the call is happening in template context, getting
22223 		 here means it's non-dependent, and a default argument is
22224 		 considered a separate definition under [temp.decls], so we can
22225 		 do this substitution without processing_template_decl.  This
22226 		 is important if the default argument contains something that
22227 		 might be instantiation-dependent like access (87480).  */
22228 	      processing_template_decl_sentinel s;
22229 	      tree substed = NULL_TREE;
22230 	      if (saw_undeduced == 1)
22231 		{
22232 		  /* First instatiate in template context, in case we still
22233 		     depend on undeduced template parameters.  */
22234 		  ++processing_template_decl;
22235 		  substed = tsubst_template_arg (arg, full_targs, complain,
22236 						 NULL_TREE);
22237 		  --processing_template_decl;
22238 		  if (substed != error_mark_node
22239 		      && !uses_template_parms (substed))
22240 		    /* We replaced all the tparms, substitute again out of
22241 		       template context.  */
22242 		    substed = NULL_TREE;
22243 		}
22244 	      if (!substed)
22245 		substed = tsubst_template_arg (arg, full_targs, complain,
22246 					       NULL_TREE);
22247 
22248 	      if (!uses_template_parms (substed))
22249 		arg = convert_template_argument (parm, substed, full_targs,
22250 						 complain, i, NULL_TREE);
22251 	      else if (saw_undeduced == 1)
22252 		arg = NULL_TREE;
22253 	      else
22254 		arg = error_mark_node;
22255 	    }
22256 
22257 	  input_location = save_loc;
22258 	  *checks = get_deferred_access_checks ();
22259 	  pop_deferring_access_checks ();
22260 
22261 	  if (arg == error_mark_node)
22262 	    return 1;
22263 	  else if (arg)
22264 	    {
22265 	      TREE_VEC_ELT (targs, i) = arg;
22266 	      /* The position of the first default template argument,
22267 		 is also the number of non-defaulted arguments in TARGS.
22268 		 Record that.  */
22269 	      if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22270 		SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
22271 	    }
22272 	}
22273 
22274       if (saw_undeduced++ == 1)
22275 	goto again;
22276     }
22277 
22278   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
22279     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
22280 
22281   return unify_success (explain_p);
22282 }
22283 
22284 /* Subroutine of type_unification_real.  Args are like the variables
22285    at the call site.  ARG is an overloaded function (or template-id);
22286    we try deducing template args from each of the overloads, and if
22287    only one succeeds, we go with that.  Modifies TARGS and returns
22288    true on success.  */
22289 
22290 static bool
resolve_overloaded_unification(tree tparms,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool explain_p)22291 resolve_overloaded_unification (tree tparms,
22292 				tree targs,
22293 				tree parm,
22294 				tree arg,
22295 				unification_kind_t strict,
22296 				int sub_strict,
22297 			        bool explain_p)
22298 {
22299   tree tempargs = copy_node (targs);
22300   int good = 0;
22301   tree goodfn = NULL_TREE;
22302   bool addr_p;
22303 
22304   if (TREE_CODE (arg) == ADDR_EXPR)
22305     {
22306       arg = TREE_OPERAND (arg, 0);
22307       addr_p = true;
22308     }
22309   else
22310     addr_p = false;
22311 
22312   if (TREE_CODE (arg) == COMPONENT_REF)
22313     /* Handle `&x' where `x' is some static or non-static member
22314        function name.  */
22315     arg = TREE_OPERAND (arg, 1);
22316 
22317   if (TREE_CODE (arg) == OFFSET_REF)
22318     arg = TREE_OPERAND (arg, 1);
22319 
22320   /* Strip baselink information.  */
22321   if (BASELINK_P (arg))
22322     arg = BASELINK_FUNCTIONS (arg);
22323 
22324   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
22325     {
22326       /* If we got some explicit template args, we need to plug them into
22327 	 the affected templates before we try to unify, in case the
22328 	 explicit args will completely resolve the templates in question.  */
22329 
22330       int ok = 0;
22331       tree expl_subargs = TREE_OPERAND (arg, 1);
22332       arg = TREE_OPERAND (arg, 0);
22333 
22334       for (lkp_iterator iter (arg); iter; ++iter)
22335 	{
22336 	  tree fn = *iter;
22337 	  tree subargs, elem;
22338 
22339 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
22340 	    continue;
22341 
22342 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22343 					   expl_subargs, NULL_TREE, tf_none,
22344 					   /*require_all_args=*/true,
22345 					   /*use_default_args=*/true);
22346 	  if (subargs != error_mark_node
22347 	      && !any_dependent_template_arguments_p (subargs))
22348 	    {
22349 	      fn = instantiate_template (fn, subargs, tf_none);
22350 	      if (!constraints_satisfied_p (fn))
22351 		continue;
22352 	      if (undeduced_auto_decl (fn))
22353 		{
22354 		  /* Instantiate the function to deduce its return type.  */
22355 		  ++function_depth;
22356 		  instantiate_decl (fn, /*defer*/false, /*class*/false);
22357 		  --function_depth;
22358 		}
22359 
22360 	      if (flag_noexcept_type)
22361 		maybe_instantiate_noexcept (fn, tf_none);
22362 
22363 	      elem = TREE_TYPE (fn);
22364 	      if (try_one_overload (tparms, targs, tempargs, parm,
22365 				    elem, strict, sub_strict, addr_p, explain_p)
22366 		  && (!goodfn || !same_type_p (goodfn, elem)))
22367 		{
22368 		  goodfn = elem;
22369 		  ++good;
22370 		}
22371 	    }
22372 	  else if (subargs)
22373 	    ++ok;
22374 	}
22375       /* If no templates (or more than one) are fully resolved by the
22376 	 explicit arguments, this template-id is a non-deduced context; it
22377 	 could still be OK if we deduce all template arguments for the
22378 	 enclosing call through other arguments.  */
22379       if (good != 1)
22380 	good = ok;
22381     }
22382   else if (!OVL_P (arg))
22383     /* If ARG is, for example, "(0, &f)" then its type will be unknown
22384        -- but the deduction does not succeed because the expression is
22385        not just the function on its own.  */
22386     return false;
22387   else
22388     for (lkp_iterator iter (arg); iter; ++iter)
22389       {
22390 	tree fn = *iter;
22391 	if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
22392 			      strict, sub_strict, addr_p, explain_p)
22393 	    && (!goodfn || !decls_match (goodfn, fn)))
22394 	  {
22395 	    goodfn = fn;
22396 	    ++good;
22397 	  }
22398       }
22399 
22400   /* [temp.deduct.type] A template-argument can be deduced from a pointer
22401      to function or pointer to member function argument if the set of
22402      overloaded functions does not contain function templates and at most
22403      one of a set of overloaded functions provides a unique match.
22404 
22405      So if we found multiple possibilities, we return success but don't
22406      deduce anything.  */
22407 
22408   if (good == 1)
22409     {
22410       int i = TREE_VEC_LENGTH (targs);
22411       for (; i--; )
22412 	if (TREE_VEC_ELT (tempargs, i))
22413 	  {
22414 	    tree old = TREE_VEC_ELT (targs, i);
22415 	    tree new_ = TREE_VEC_ELT (tempargs, i);
22416 	    if (new_ && old && ARGUMENT_PACK_P (old)
22417 		&& ARGUMENT_PACK_EXPLICIT_ARGS (old))
22418 	      /* Don't forget explicit template arguments in a pack.  */
22419 	      ARGUMENT_PACK_EXPLICIT_ARGS (new_)
22420 		= ARGUMENT_PACK_EXPLICIT_ARGS (old);
22421 	    TREE_VEC_ELT (targs, i) = new_;
22422 	  }
22423     }
22424   if (good)
22425     return true;
22426 
22427   return false;
22428 }
22429 
22430 /* Core DR 115: In contexts where deduction is done and fails, or in
22431    contexts where deduction is not done, if a template argument list is
22432    specified and it, along with any default template arguments, identifies
22433    a single function template specialization, then the template-id is an
22434    lvalue for the function template specialization.  */
22435 
22436 tree
resolve_nondeduced_context(tree orig_expr,tsubst_flags_t complain)22437 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
22438 {
22439   tree expr, offset, baselink;
22440   bool addr;
22441 
22442   if (!type_unknown_p (orig_expr))
22443     return orig_expr;
22444 
22445   expr = orig_expr;
22446   addr = false;
22447   offset = NULL_TREE;
22448   baselink = NULL_TREE;
22449 
22450   if (TREE_CODE (expr) == ADDR_EXPR)
22451     {
22452       expr = TREE_OPERAND (expr, 0);
22453       addr = true;
22454     }
22455   if (TREE_CODE (expr) == OFFSET_REF)
22456     {
22457       offset = expr;
22458       expr = TREE_OPERAND (expr, 1);
22459     }
22460   if (BASELINK_P (expr))
22461     {
22462       baselink = expr;
22463       expr = BASELINK_FUNCTIONS (expr);
22464     }
22465 
22466   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
22467     {
22468       int good = 0;
22469       tree goodfn = NULL_TREE;
22470 
22471       /* If we got some explicit template args, we need to plug them into
22472 	 the affected templates before we try to unify, in case the
22473 	 explicit args will completely resolve the templates in question.  */
22474 
22475       tree expl_subargs = TREE_OPERAND (expr, 1);
22476       tree arg = TREE_OPERAND (expr, 0);
22477       tree badfn = NULL_TREE;
22478       tree badargs = NULL_TREE;
22479 
22480       for (lkp_iterator iter (arg); iter; ++iter)
22481 	{
22482 	  tree fn = *iter;
22483 	  tree subargs, elem;
22484 
22485 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
22486 	    continue;
22487 
22488 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
22489 					   expl_subargs, NULL_TREE, tf_none,
22490 					   /*require_all_args=*/true,
22491 					   /*use_default_args=*/true);
22492 	  if (subargs != error_mark_node
22493 	      && !any_dependent_template_arguments_p (subargs))
22494 	    {
22495 	      elem = instantiate_template (fn, subargs, tf_none);
22496 	      if (elem == error_mark_node)
22497 		{
22498 		  badfn = fn;
22499 		  badargs = subargs;
22500 		}
22501 	      else if (elem && (!goodfn || !decls_match (goodfn, elem))
22502 		       && constraints_satisfied_p (elem))
22503 		{
22504 		  goodfn = elem;
22505 		  ++good;
22506 		}
22507 	    }
22508 	}
22509       if (good == 1)
22510 	{
22511 	  mark_used (goodfn);
22512 	  expr = goodfn;
22513 	  if (baselink)
22514 	    expr = build_baselink (BASELINK_BINFO (baselink),
22515 				   BASELINK_ACCESS_BINFO (baselink),
22516 				   expr, BASELINK_OPTYPE (baselink));
22517 	  if (offset)
22518 	    {
22519 	      tree base
22520 		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
22521 	      expr = build_offset_ref (base, expr, addr, complain);
22522 	    }
22523 	  if (addr)
22524 	    expr = cp_build_addr_expr (expr, complain);
22525 	  return expr;
22526 	}
22527       else if (good == 0 && badargs && (complain & tf_error))
22528 	/* There were no good options and at least one bad one, so let the
22529 	   user know what the problem is.  */
22530 	instantiate_template (badfn, badargs, complain);
22531     }
22532   return orig_expr;
22533 }
22534 
22535 /* As above, but error out if the expression remains overloaded.  */
22536 
22537 tree
resolve_nondeduced_context_or_error(tree exp,tsubst_flags_t complain)22538 resolve_nondeduced_context_or_error (tree exp, tsubst_flags_t complain)
22539 {
22540   exp = resolve_nondeduced_context (exp, complain);
22541   if (type_unknown_p (exp))
22542     {
22543       if (complain & tf_error)
22544 	cxx_incomplete_type_error (exp, TREE_TYPE (exp));
22545       return error_mark_node;
22546     }
22547   return exp;
22548 }
22549 
22550 /* Subroutine of resolve_overloaded_unification; does deduction for a single
22551    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
22552    different overloads deduce different arguments for a given parm.
22553    ADDR_P is true if the expression for which deduction is being
22554    performed was of the form "& fn" rather than simply "fn".
22555 
22556    Returns 1 on success.  */
22557 
22558 static int
try_one_overload(tree tparms,tree orig_targs,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool addr_p,bool explain_p)22559 try_one_overload (tree tparms,
22560 		  tree orig_targs,
22561 		  tree targs,
22562 		  tree parm,
22563 		  tree arg,
22564 		  unification_kind_t strict,
22565 		  int sub_strict,
22566 		  bool addr_p,
22567 		  bool explain_p)
22568 {
22569   int nargs;
22570   tree tempargs;
22571   int i;
22572 
22573   if (arg == error_mark_node)
22574     return 0;
22575 
22576   /* [temp.deduct.type] A template-argument can be deduced from a pointer
22577      to function or pointer to member function argument if the set of
22578      overloaded functions does not contain function templates and at most
22579      one of a set of overloaded functions provides a unique match.
22580 
22581      So if this is a template, just return success.  */
22582 
22583   if (uses_template_parms (arg))
22584     return 1;
22585 
22586   if (TREE_CODE (arg) == METHOD_TYPE)
22587     arg = build_ptrmemfunc_type (build_pointer_type (arg));
22588   else if (addr_p)
22589     arg = build_pointer_type (arg);
22590 
22591   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
22592 
22593   /* We don't copy orig_targs for this because if we have already deduced
22594      some template args from previous args, unify would complain when we
22595      try to deduce a template parameter for the same argument, even though
22596      there isn't really a conflict.  */
22597   nargs = TREE_VEC_LENGTH (targs);
22598   tempargs = make_tree_vec (nargs);
22599 
22600   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
22601     return 0;
22602 
22603   /* First make sure we didn't deduce anything that conflicts with
22604      explicitly specified args.  */
22605   for (i = nargs; i--; )
22606     {
22607       tree elt = TREE_VEC_ELT (tempargs, i);
22608       tree oldelt = TREE_VEC_ELT (orig_targs, i);
22609 
22610       if (!elt)
22611 	/*NOP*/;
22612       else if (uses_template_parms (elt))
22613 	/* Since we're unifying against ourselves, we will fill in
22614 	   template args used in the function parm list with our own
22615 	   template parms.  Discard them.  */
22616 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
22617       else if (oldelt && ARGUMENT_PACK_P (oldelt))
22618 	{
22619 	  /* Check that the argument at each index of the deduced argument pack
22620 	     is equivalent to the corresponding explicitly specified argument.
22621 	     We may have deduced more arguments than were explicitly specified,
22622 	     and that's OK.  */
22623 
22624 	  /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
22625 	     that's wrong if we deduce the same argument pack from multiple
22626 	     function arguments: it's only incomplete the first time.  */
22627 
22628 	  tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
22629 	  tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
22630 
22631 	  if (TREE_VEC_LENGTH (deduced_pack)
22632 	      < TREE_VEC_LENGTH (explicit_pack))
22633 	    return 0;
22634 
22635 	  for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
22636 	    if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
22637 				      TREE_VEC_ELT (deduced_pack, j)))
22638 	      return 0;
22639 	}
22640       else if (oldelt && !template_args_equal (oldelt, elt))
22641 	return 0;
22642     }
22643 
22644   for (i = nargs; i--; )
22645     {
22646       tree elt = TREE_VEC_ELT (tempargs, i);
22647 
22648       if (elt)
22649 	TREE_VEC_ELT (targs, i) = elt;
22650     }
22651 
22652   return 1;
22653 }
22654 
22655 /* PARM is a template class (perhaps with unbound template
22656    parameters).  ARG is a fully instantiated type.  If ARG can be
22657    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
22658    TARGS are as for unify.  */
22659 
22660 static tree
try_class_unification(tree tparms,tree targs,tree parm,tree arg,bool explain_p)22661 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
22662 		       bool explain_p)
22663 {
22664   tree copy_of_targs;
22665 
22666   if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
22667     return NULL_TREE;
22668   else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22669     /* Matches anything.  */;
22670   else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
22671 	   != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
22672     return NULL_TREE;
22673 
22674   /* We need to make a new template argument vector for the call to
22675      unify.  If we used TARGS, we'd clutter it up with the result of
22676      the attempted unification, even if this class didn't work out.
22677      We also don't want to commit ourselves to all the unifications
22678      we've already done, since unification is supposed to be done on
22679      an argument-by-argument basis.  In other words, consider the
22680      following pathological case:
22681 
22682        template <int I, int J, int K>
22683        struct S {};
22684 
22685        template <int I, int J>
22686        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
22687 
22688        template <int I, int J, int K>
22689        void f(S<I, J, K>, S<I, I, I>);
22690 
22691        void g() {
22692 	 S<0, 0, 0> s0;
22693 	 S<0, 1, 2> s2;
22694 
22695 	 f(s0, s2);
22696        }
22697 
22698      Now, by the time we consider the unification involving `s2', we
22699      already know that we must have `f<0, 0, 0>'.  But, even though
22700      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
22701      because there are two ways to unify base classes of S<0, 1, 2>
22702      with S<I, I, I>.  If we kept the already deduced knowledge, we
22703      would reject the possibility I=1.  */
22704   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
22705 
22706   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22707     {
22708       if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
22709 	return NULL_TREE;
22710       return arg;
22711     }
22712 
22713   /* If unification failed, we're done.  */
22714   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
22715 	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
22716     return NULL_TREE;
22717 
22718   return arg;
22719 }
22720 
22721 /* Given a template type PARM and a class type ARG, find the unique
22722    base type in ARG that is an instance of PARM.  We do not examine
22723    ARG itself; only its base-classes.  If there is not exactly one
22724    appropriate base class, return NULL_TREE.  PARM may be the type of
22725    a partial specialization, as well as a plain template type.  Used
22726    by unify.  */
22727 
22728 static enum template_base_result
get_template_base(tree tparms,tree targs,tree parm,tree arg,bool explain_p,tree * result)22729 get_template_base (tree tparms, tree targs, tree parm, tree arg,
22730 		   bool explain_p, tree *result)
22731 {
22732   tree rval = NULL_TREE;
22733   tree binfo;
22734 
22735   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
22736 
22737   binfo = TYPE_BINFO (complete_type (arg));
22738   if (!binfo)
22739     {
22740       /* The type could not be completed.  */
22741       *result = NULL_TREE;
22742       return tbr_incomplete_type;
22743     }
22744 
22745   /* Walk in inheritance graph order.  The search order is not
22746      important, and this avoids multiple walks of virtual bases.  */
22747   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
22748     {
22749       tree r = try_class_unification (tparms, targs, parm,
22750 				      BINFO_TYPE (binfo), explain_p);
22751 
22752       if (r)
22753 	{
22754 	  /* If there is more than one satisfactory baseclass, then:
22755 
22756 	       [temp.deduct.call]
22757 
22758 	      If they yield more than one possible deduced A, the type
22759 	      deduction fails.
22760 
22761 	     applies.  */
22762 	  if (rval && !same_type_p (r, rval))
22763 	    {
22764 	      *result = NULL_TREE;
22765 	      return tbr_ambiguous_baseclass;
22766 	    }
22767 
22768 	  rval = r;
22769 	}
22770     }
22771 
22772   *result = rval;
22773   return tbr_success;
22774 }
22775 
22776 /* Returns the level of DECL, which declares a template parameter.  */
22777 
22778 static int
template_decl_level(tree decl)22779 template_decl_level (tree decl)
22780 {
22781   switch (TREE_CODE (decl))
22782     {
22783     case TYPE_DECL:
22784     case TEMPLATE_DECL:
22785       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
22786 
22787     case PARM_DECL:
22788       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
22789 
22790     default:
22791       gcc_unreachable ();
22792     }
22793   return 0;
22794 }
22795 
22796 /* Decide whether ARG can be unified with PARM, considering only the
22797    cv-qualifiers of each type, given STRICT as documented for unify.
22798    Returns nonzero iff the unification is OK on that basis.  */
22799 
22800 static int
check_cv_quals_for_unify(int strict,tree arg,tree parm)22801 check_cv_quals_for_unify (int strict, tree arg, tree parm)
22802 {
22803   int arg_quals = cp_type_quals (arg);
22804   int parm_quals = cp_type_quals (parm);
22805 
22806   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
22807       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
22808     {
22809       /*  Although a CVR qualifier is ignored when being applied to a
22810 	  substituted template parameter ([8.3.2]/1 for example), that
22811 	  does not allow us to unify "const T" with "int&" because both
22812 	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
22813 	  It is ok when we're allowing additional CV qualifiers
22814 	  at the outer level [14.8.2.1]/3,1st bullet.  */
22815       if ((TYPE_REF_P (arg)
22816 	   || FUNC_OR_METHOD_TYPE_P (arg))
22817 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
22818 	return 0;
22819 
22820       if ((!INDIRECT_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
22821 	  && (parm_quals & TYPE_QUAL_RESTRICT))
22822 	return 0;
22823     }
22824 
22825   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
22826       && (arg_quals & parm_quals) != parm_quals)
22827     return 0;
22828 
22829   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
22830       && (parm_quals & arg_quals) != arg_quals)
22831     return 0;
22832 
22833   return 1;
22834 }
22835 
22836 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
22837 void
template_parm_level_and_index(tree parm,int * level,int * index)22838 template_parm_level_and_index (tree parm, int* level, int* index)
22839 {
22840   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
22841       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
22842       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
22843     {
22844       *index = TEMPLATE_TYPE_IDX (parm);
22845       *level = TEMPLATE_TYPE_LEVEL (parm);
22846     }
22847   else
22848     {
22849       *index = TEMPLATE_PARM_IDX (parm);
22850       *level = TEMPLATE_PARM_LEVEL (parm);
22851     }
22852 }
22853 
22854 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
22855   do {									\
22856     if (unify (TP, TA, P, A, S, EP))					\
22857       return 1;								\
22858   } while (0)
22859 
22860 /* Unifies the remaining arguments in PACKED_ARGS with the pack
22861    expansion at the end of PACKED_PARMS. Returns 0 if the type
22862    deduction succeeds, 1 otherwise. STRICT is the same as in
22863    fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
22864    function call argument list. We'll need to adjust the arguments to make them
22865    types. SUBR tells us if this is from a recursive call to
22866    type_unification_real, or for comparing two template argument
22867    lists. */
22868 
22869 static int
unify_pack_expansion(tree tparms,tree targs,tree packed_parms,tree packed_args,unification_kind_t strict,bool subr,bool explain_p)22870 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
22871                       tree packed_args, unification_kind_t strict,
22872                       bool subr, bool explain_p)
22873 {
22874   tree parm
22875     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
22876   tree pattern = PACK_EXPANSION_PATTERN (parm);
22877   tree pack, packs = NULL_TREE;
22878   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
22879 
22880   /* Add in any args remembered from an earlier partial instantiation.  */
22881   targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
22882   int levels = TMPL_ARGS_DEPTH (targs);
22883 
22884   packed_args = expand_template_argument_pack (packed_args);
22885 
22886   int len = TREE_VEC_LENGTH (packed_args);
22887 
22888   /* Determine the parameter packs we will be deducing from the
22889      pattern, and record their current deductions.  */
22890   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
22891        pack; pack = TREE_CHAIN (pack))
22892     {
22893       tree parm_pack = TREE_VALUE (pack);
22894       int idx, level;
22895 
22896       /* Only template parameter packs can be deduced, not e.g. function
22897 	 parameter packs or __bases or __integer_pack.  */
22898       if (!TEMPLATE_PARM_P (parm_pack))
22899 	continue;
22900 
22901       /* Determine the index and level of this parameter pack.  */
22902       template_parm_level_and_index (parm_pack, &level, &idx);
22903       if (level < levels)
22904 	continue;
22905 
22906       /* Keep track of the parameter packs and their corresponding
22907          argument packs.  */
22908       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
22909       TREE_TYPE (packs) = make_tree_vec (len - start);
22910     }
22911 
22912   /* Loop through all of the arguments that have not yet been
22913      unified and unify each with the pattern.  */
22914   for (i = start; i < len; i++)
22915     {
22916       tree parm;
22917       bool any_explicit = false;
22918       tree arg = TREE_VEC_ELT (packed_args, i);
22919 
22920       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
22921 	 or the element of its argument pack at the current index if
22922 	 this argument was explicitly specified.  */
22923       for (pack = packs; pack; pack = TREE_CHAIN (pack))
22924         {
22925           int idx, level;
22926           tree arg, pargs;
22927           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
22928 
22929           arg = NULL_TREE;
22930           if (TREE_VALUE (pack)
22931               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
22932               && (i - start < TREE_VEC_LENGTH (pargs)))
22933             {
22934               any_explicit = true;
22935               arg = TREE_VEC_ELT (pargs, i - start);
22936             }
22937           TMPL_ARG (targs, level, idx) = arg;
22938         }
22939 
22940       /* If we had explicit template arguments, substitute them into the
22941 	 pattern before deduction.  */
22942       if (any_explicit)
22943 	{
22944 	  /* Some arguments might still be unspecified or dependent.  */
22945 	  bool dependent;
22946 	  ++processing_template_decl;
22947 	  dependent = any_dependent_template_arguments_p (targs);
22948 	  if (!dependent)
22949 	    --processing_template_decl;
22950 	  parm = tsubst (pattern, targs,
22951 			 explain_p ? tf_warning_or_error : tf_none,
22952 			 NULL_TREE);
22953 	  if (dependent)
22954 	    --processing_template_decl;
22955 	  if (parm == error_mark_node)
22956 	    return 1;
22957 	}
22958       else
22959 	parm = pattern;
22960 
22961       /* Unify the pattern with the current argument.  */
22962       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
22963 			      explain_p))
22964 	return 1;
22965 
22966       /* For each parameter pack, collect the deduced value.  */
22967       for (pack = packs; pack; pack = TREE_CHAIN (pack))
22968         {
22969           int idx, level;
22970           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
22971 
22972           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
22973             TMPL_ARG (targs, level, idx);
22974         }
22975     }
22976 
22977   /* Verify that the results of unification with the parameter packs
22978      produce results consistent with what we've seen before, and make
22979      the deduced argument packs available.  */
22980   for (pack = packs; pack; pack = TREE_CHAIN (pack))
22981     {
22982       tree old_pack = TREE_VALUE (pack);
22983       tree new_args = TREE_TYPE (pack);
22984       int i, len = TREE_VEC_LENGTH (new_args);
22985       int idx, level;
22986       bool nondeduced_p = false;
22987 
22988       /* By default keep the original deduced argument pack.
22989 	 If necessary, more specific code is going to update the
22990 	 resulting deduced argument later down in this function.  */
22991       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
22992       TMPL_ARG (targs, level, idx) = old_pack;
22993 
22994       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
22995 	 actually deduce anything.  */
22996       for (i = 0; i < len && !nondeduced_p; ++i)
22997 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
22998 	  nondeduced_p = true;
22999       if (nondeduced_p)
23000 	continue;
23001 
23002       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
23003         {
23004           /* If we had fewer function args than explicit template args,
23005              just use the explicits.  */
23006           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23007           int explicit_len = TREE_VEC_LENGTH (explicit_args);
23008           if (len < explicit_len)
23009             new_args = explicit_args;
23010         }
23011 
23012       if (!old_pack)
23013         {
23014           tree result;
23015           /* Build the deduced *_ARGUMENT_PACK.  */
23016           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
23017             {
23018               result = make_node (NONTYPE_ARGUMENT_PACK);
23019               TREE_CONSTANT (result) = 1;
23020             }
23021           else
23022             result = cxx_make_type (TYPE_ARGUMENT_PACK);
23023 
23024           SET_ARGUMENT_PACK_ARGS (result, new_args);
23025 
23026           /* Note the deduced argument packs for this parameter
23027              pack.  */
23028           TMPL_ARG (targs, level, idx) = result;
23029         }
23030       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
23031                && (ARGUMENT_PACK_ARGS (old_pack)
23032                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
23033         {
23034           /* We only had the explicitly-provided arguments before, but
23035              now we have a complete set of arguments.  */
23036           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
23037 
23038           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
23039           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
23040           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
23041         }
23042       else
23043 	{
23044 	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
23045 	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
23046 
23047 	  if (!comp_template_args (old_args, new_args,
23048 				   &bad_old_arg, &bad_new_arg))
23049 	    /* Inconsistent unification of this parameter pack.  */
23050 	    return unify_parameter_pack_inconsistent (explain_p,
23051 						      bad_old_arg,
23052 						      bad_new_arg);
23053 	}
23054     }
23055 
23056   return unify_success (explain_p);
23057 }
23058 
23059 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
23060    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
23061    parameters and return value are as for unify.  */
23062 
23063 static int
unify_array_domain(tree tparms,tree targs,tree parm_dom,tree arg_dom,bool explain_p)23064 unify_array_domain (tree tparms, tree targs,
23065 		    tree parm_dom, tree arg_dom,
23066 		    bool explain_p)
23067 {
23068   tree parm_max;
23069   tree arg_max;
23070   bool parm_cst;
23071   bool arg_cst;
23072 
23073   /* Our representation of array types uses "N - 1" as the
23074      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
23075      not an integer constant.  We cannot unify arbitrarily
23076      complex expressions, so we eliminate the MINUS_EXPRs
23077      here.  */
23078   parm_max = TYPE_MAX_VALUE (parm_dom);
23079   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
23080   if (!parm_cst)
23081     {
23082       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
23083       parm_max = TREE_OPERAND (parm_max, 0);
23084     }
23085   arg_max = TYPE_MAX_VALUE (arg_dom);
23086   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
23087   if (!arg_cst)
23088     {
23089       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
23090 	 trying to unify the type of a variable with the type
23091 	 of a template parameter.  For example:
23092 
23093 	   template <unsigned int N>
23094 	   void f (char (&) [N]);
23095 	   int g();
23096 	   void h(int i) {
23097 	     char a[g(i)];
23098 	     f(a);
23099 	   }
23100 
23101 	 Here, the type of the ARG will be "int [g(i)]", and
23102 	 may be a SAVE_EXPR, etc.  */
23103       if (TREE_CODE (arg_max) != MINUS_EXPR)
23104 	return unify_vla_arg (explain_p, arg_dom);
23105       arg_max = TREE_OPERAND (arg_max, 0);
23106     }
23107 
23108   /* If only one of the bounds used a MINUS_EXPR, compensate
23109      by adding one to the other bound.  */
23110   if (parm_cst && !arg_cst)
23111     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
23112 				integer_type_node,
23113 				parm_max,
23114 				integer_one_node);
23115   else if (arg_cst && !parm_cst)
23116     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
23117 			       integer_type_node,
23118 			       arg_max,
23119 			       integer_one_node);
23120 
23121   return unify (tparms, targs, parm_max, arg_max,
23122 		UNIFY_ALLOW_INTEGER, explain_p);
23123 }
23124 
23125 /* Returns whether T, a P or A in unify, is a type, template or expression.  */
23126 
23127 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
23128 
23129 static pa_kind_t
pa_kind(tree t)23130 pa_kind (tree t)
23131 {
23132   if (PACK_EXPANSION_P (t))
23133     t = PACK_EXPANSION_PATTERN (t);
23134   if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
23135       || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
23136       || DECL_TYPE_TEMPLATE_P (t))
23137     return pa_tmpl;
23138   else if (TYPE_P (t))
23139     return pa_type;
23140   else
23141     return pa_expr;
23142 }
23143 
23144 /* Deduce the value of template parameters.  TPARMS is the (innermost)
23145    set of template parameters to a template.  TARGS is the bindings
23146    for those template parameters, as determined thus far; TARGS may
23147    include template arguments for outer levels of template parameters
23148    as well.  PARM is a parameter to a template function, or a
23149    subcomponent of that parameter; ARG is the corresponding argument.
23150    This function attempts to match PARM with ARG in a manner
23151    consistent with the existing assignments in TARGS.  If more values
23152    are deduced, then TARGS is updated.
23153 
23154    Returns 0 if the type deduction succeeds, 1 otherwise.  The
23155    parameter STRICT is a bitwise or of the following flags:
23156 
23157      UNIFY_ALLOW_NONE:
23158        Require an exact match between PARM and ARG.
23159      UNIFY_ALLOW_MORE_CV_QUAL:
23160        Allow the deduced ARG to be more cv-qualified (by qualification
23161        conversion) than ARG.
23162      UNIFY_ALLOW_LESS_CV_QUAL:
23163        Allow the deduced ARG to be less cv-qualified than ARG.
23164      UNIFY_ALLOW_DERIVED:
23165        Allow the deduced ARG to be a template base class of ARG,
23166        or a pointer to a template base class of the type pointed to by
23167        ARG.
23168      UNIFY_ALLOW_INTEGER:
23169        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
23170        case for more information.
23171      UNIFY_ALLOW_OUTER_LEVEL:
23172        This is the outermost level of a deduction. Used to determine validity
23173        of qualification conversions. A valid qualification conversion must
23174        have const qualified pointers leading up to the inner type which
23175        requires additional CV quals, except at the outer level, where const
23176        is not required [conv.qual]. It would be normal to set this flag in
23177        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
23178      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
23179        This is the outermost level of a deduction, and PARM can be more CV
23180        qualified at this point.
23181      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
23182        This is the outermost level of a deduction, and PARM can be less CV
23183        qualified at this point.  */
23184 
23185 static int
unify(tree tparms,tree targs,tree parm,tree arg,int strict,bool explain_p)23186 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
23187        bool explain_p)
23188 {
23189   int idx;
23190   tree targ;
23191   tree tparm;
23192   int strict_in = strict;
23193   tsubst_flags_t complain = (explain_p
23194 			     ? tf_warning_or_error
23195 			     : tf_none);
23196 
23197   /* I don't think this will do the right thing with respect to types.
23198      But the only case I've seen it in so far has been array bounds, where
23199      signedness is the only information lost, and I think that will be
23200      okay.  VIEW_CONVERT_EXPR can appear with class NTTP, thanks to
23201      finish_id_expression_1, and are also OK.  */
23202   while (CONVERT_EXPR_P (parm) || TREE_CODE (parm) == VIEW_CONVERT_EXPR)
23203     parm = TREE_OPERAND (parm, 0);
23204 
23205   if (arg == error_mark_node)
23206     return unify_invalid (explain_p);
23207   if (arg == unknown_type_node
23208       || arg == init_list_type_node)
23209     /* We can't deduce anything from this, but we might get all the
23210        template args from other function args.  */
23211     return unify_success (explain_p);
23212 
23213   if (parm == any_targ_node || arg == any_targ_node)
23214     return unify_success (explain_p);
23215 
23216   /* If PARM uses template parameters, then we can't bail out here,
23217      even if ARG == PARM, since we won't record unifications for the
23218      template parameters.  We might need them if we're trying to
23219      figure out which of two things is more specialized.  */
23220   if (arg == parm && !uses_template_parms (parm))
23221     return unify_success (explain_p);
23222 
23223   /* Handle init lists early, so the rest of the function can assume
23224      we're dealing with a type. */
23225   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
23226     {
23227       tree elt, elttype;
23228       unsigned i;
23229       tree orig_parm = parm;
23230 
23231       if (!is_std_init_list (parm)
23232 	  && TREE_CODE (parm) != ARRAY_TYPE)
23233 	/* We can only deduce from an initializer list argument if the
23234 	   parameter is std::initializer_list or an array; otherwise this
23235 	   is a non-deduced context. */
23236 	return unify_success (explain_p);
23237 
23238       if (TREE_CODE (parm) == ARRAY_TYPE)
23239 	elttype = TREE_TYPE (parm);
23240       else
23241 	{
23242 	  elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
23243 	  /* Deduction is defined in terms of a single type, so just punt
23244 	     on the (bizarre) std::initializer_list<T...>.  */
23245 	  if (PACK_EXPANSION_P (elttype))
23246 	    return unify_success (explain_p);
23247 	}
23248 
23249       if (strict != DEDUCE_EXACT
23250 	  && TYPE_P (elttype)
23251 	  && !uses_deducible_template_parms (elttype))
23252 	/* If ELTTYPE has no deducible template parms, skip deduction from
23253 	   the list elements.  */;
23254       else
23255 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
23256 	  {
23257 	    int elt_strict = strict;
23258 
23259 	    if (elt == error_mark_node)
23260 	      return unify_invalid (explain_p);
23261 
23262 	    if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
23263 	      {
23264 		tree type = TREE_TYPE (elt);
23265 		if (type == error_mark_node)
23266 		  return unify_invalid (explain_p);
23267 		/* It should only be possible to get here for a call.  */
23268 		gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
23269 		elt_strict |= maybe_adjust_types_for_deduction
23270 		  (DEDUCE_CALL, &elttype, &type, elt);
23271 		elt = type;
23272 	      }
23273 
23274 	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
23275 				   explain_p);
23276 	}
23277 
23278       if (TREE_CODE (parm) == ARRAY_TYPE
23279 	  && deducible_array_bound (TYPE_DOMAIN (parm)))
23280 	{
23281 	  /* Also deduce from the length of the initializer list.  */
23282 	  tree max = size_int (CONSTRUCTOR_NELTS (arg));
23283 	  tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
23284 	  if (idx == error_mark_node)
23285 	    return unify_invalid (explain_p);
23286 	  return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
23287 				     idx, explain_p);
23288 	}
23289 
23290       /* If the std::initializer_list<T> deduction worked, replace the
23291 	 deduced A with std::initializer_list<A>.  */
23292       if (orig_parm != parm)
23293 	{
23294 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
23295 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23296 	  targ = listify (targ);
23297 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
23298 	}
23299       return unify_success (explain_p);
23300     }
23301 
23302   /* If parm and arg aren't the same kind of thing (template, type, or
23303      expression), fail early.  */
23304   if (pa_kind (parm) != pa_kind (arg))
23305     return unify_invalid (explain_p);
23306 
23307   /* Immediately reject some pairs that won't unify because of
23308      cv-qualification mismatches.  */
23309   if (TREE_CODE (arg) == TREE_CODE (parm)
23310       && TYPE_P (arg)
23311       /* It is the elements of the array which hold the cv quals of an array
23312 	 type, and the elements might be template type parms. We'll check
23313 	 when we recurse.  */
23314       && TREE_CODE (arg) != ARRAY_TYPE
23315       /* We check the cv-qualifiers when unifying with template type
23316 	 parameters below.  We want to allow ARG `const T' to unify with
23317 	 PARM `T' for example, when computing which of two templates
23318 	 is more specialized, for example.  */
23319       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
23320       && !check_cv_quals_for_unify (strict_in, arg, parm))
23321     return unify_cv_qual_mismatch (explain_p, parm, arg);
23322 
23323   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
23324       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
23325     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
23326   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
23327   strict &= ~UNIFY_ALLOW_DERIVED;
23328   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
23329   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
23330 
23331   switch (TREE_CODE (parm))
23332     {
23333     case TYPENAME_TYPE:
23334     case SCOPE_REF:
23335     case UNBOUND_CLASS_TEMPLATE:
23336       /* In a type which contains a nested-name-specifier, template
23337 	 argument values cannot be deduced for template parameters used
23338 	 within the nested-name-specifier.  */
23339       return unify_success (explain_p);
23340 
23341     case TEMPLATE_TYPE_PARM:
23342     case TEMPLATE_TEMPLATE_PARM:
23343     case BOUND_TEMPLATE_TEMPLATE_PARM:
23344       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
23345       if (error_operand_p (tparm))
23346 	return unify_invalid (explain_p);
23347 
23348       if (TEMPLATE_TYPE_LEVEL (parm)
23349 	  != template_decl_level (tparm))
23350 	/* The PARM is not one we're trying to unify.  Just check
23351 	   to see if it matches ARG.  */
23352 	{
23353 	  if (TREE_CODE (arg) == TREE_CODE (parm)
23354 	      && (is_auto (parm) ? is_auto (arg)
23355 		  : same_type_p (parm, arg)))
23356 	    return unify_success (explain_p);
23357 	  else
23358 	    return unify_type_mismatch (explain_p, parm, arg);
23359 	}
23360       idx = TEMPLATE_TYPE_IDX (parm);
23361       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23362       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
23363       if (error_operand_p (tparm))
23364 	return unify_invalid (explain_p);
23365 
23366       /* Check for mixed types and values.  */
23367       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
23368 	   && TREE_CODE (tparm) != TYPE_DECL)
23369 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23370 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
23371 	gcc_unreachable ();
23372 
23373       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23374 	{
23375 	  if ((strict_in & UNIFY_ALLOW_DERIVED)
23376 	      && CLASS_TYPE_P (arg))
23377 	    {
23378 	      /* First try to match ARG directly.  */
23379 	      tree t = try_class_unification (tparms, targs, parm, arg,
23380 					      explain_p);
23381 	      if (!t)
23382 		{
23383 		  /* Otherwise, look for a suitable base of ARG, as below.  */
23384 		  enum template_base_result r;
23385 		  r = get_template_base (tparms, targs, parm, arg,
23386 					 explain_p, &t);
23387 		  if (!t)
23388 		    return unify_no_common_base (explain_p, r, parm, arg);
23389 		  arg = t;
23390 		}
23391 	    }
23392 	  /* ARG must be constructed from a template class or a template
23393 	     template parameter.  */
23394 	  else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
23395 		   && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
23396 	    return unify_template_deduction_failure (explain_p, parm, arg);
23397 
23398 	  /* Deduce arguments T, i from TT<T> or TT<i>.  */
23399 	  if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
23400 	    return 1;
23401 
23402 	  arg = TYPE_TI_TEMPLATE (arg);
23403 
23404 	  /* Fall through to deduce template name.  */
23405 	}
23406 
23407       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
23408 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
23409 	{
23410 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
23411 
23412 	  /* Simple cases: Value already set, does match or doesn't.  */
23413 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
23414 	    return unify_success (explain_p);
23415 	  else if (targ)
23416 	    return unify_inconsistency (explain_p, parm, targ, arg);
23417 	}
23418       else
23419 	{
23420 	  /* If PARM is `const T' and ARG is only `int', we don't have
23421 	     a match unless we are allowing additional qualification.
23422 	     If ARG is `const int' and PARM is just `T' that's OK;
23423 	     that binds `const int' to `T'.  */
23424 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
23425 					 arg, parm))
23426 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
23427 
23428 	  /* Consider the case where ARG is `const volatile int' and
23429 	     PARM is `const T'.  Then, T should be `volatile int'.  */
23430 	  arg = cp_build_qualified_type_real
23431 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
23432 	  if (arg == error_mark_node)
23433 	    return unify_invalid (explain_p);
23434 
23435 	  /* Simple cases: Value already set, does match or doesn't.  */
23436 	  if (targ != NULL_TREE && same_type_p (targ, arg))
23437 	    return unify_success (explain_p);
23438 	  else if (targ)
23439 	    return unify_inconsistency (explain_p, parm, targ, arg);
23440 
23441 	  /* Make sure that ARG is not a variable-sized array.  (Note
23442 	     that were talking about variable-sized arrays (like
23443 	     `int[n]'), rather than arrays of unknown size (like
23444 	     `int[]').)  We'll get very confused by such a type since
23445 	     the bound of the array is not constant, and therefore
23446 	     not mangleable.  Besides, such types are not allowed in
23447 	     ISO C++, so we can do as we please here.  We do allow
23448 	     them for 'auto' deduction, since that isn't ABI-exposed.  */
23449 	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
23450 	    return unify_vla_arg (explain_p, arg);
23451 
23452 	  /* Strip typedefs as in convert_template_argument.  */
23453 	  arg = canonicalize_type_argument (arg, tf_none);
23454 	}
23455 
23456       /* If ARG is a parameter pack or an expansion, we cannot unify
23457 	 against it unless PARM is also a parameter pack.  */
23458       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
23459 	  && !template_parameter_pack_p (parm))
23460 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
23461 
23462       /* If the argument deduction results is a METHOD_TYPE,
23463          then there is a problem.
23464          METHOD_TYPE doesn't map to any real C++ type the result of
23465 	 the deduction cannot be of that type.  */
23466       if (TREE_CODE (arg) == METHOD_TYPE)
23467 	return unify_method_type_error (explain_p, arg);
23468 
23469       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
23470       return unify_success (explain_p);
23471 
23472     case TEMPLATE_PARM_INDEX:
23473       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
23474       if (error_operand_p (tparm))
23475 	return unify_invalid (explain_p);
23476 
23477       if (TEMPLATE_PARM_LEVEL (parm)
23478 	  != template_decl_level (tparm))
23479 	{
23480 	  /* The PARM is not one we're trying to unify.  Just check
23481 	     to see if it matches ARG.  */
23482 	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
23483 			 && cp_tree_equal (parm, arg));
23484 	  if (result)
23485 	    unify_expression_unequal (explain_p, parm, arg);
23486 	  return result;
23487 	}
23488 
23489       idx = TEMPLATE_PARM_IDX (parm);
23490       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
23491 
23492       if (targ)
23493 	{
23494 	  if ((strict & UNIFY_ALLOW_INTEGER)
23495 	      && TREE_TYPE (targ) && TREE_TYPE (arg)
23496 	      && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
23497 	    /* We're deducing from an array bound, the type doesn't matter.  */
23498 	    arg = fold_convert (TREE_TYPE (targ), arg);
23499 	  int x = !cp_tree_equal (targ, arg);
23500 	  if (x)
23501 	    unify_inconsistency (explain_p, parm, targ, arg);
23502 	  return x;
23503 	}
23504 
23505       /* [temp.deduct.type] If, in the declaration of a function template
23506 	 with a non-type template-parameter, the non-type
23507 	 template-parameter is used in an expression in the function
23508 	 parameter-list and, if the corresponding template-argument is
23509 	 deduced, the template-argument type shall match the type of the
23510 	 template-parameter exactly, except that a template-argument
23511 	 deduced from an array bound may be of any integral type.
23512 	 The non-type parameter might use already deduced type parameters.  */
23513       tparm = TREE_TYPE (parm);
23514       if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
23515 	/* We don't have enough levels of args to do any substitution.  This
23516 	   can happen in the context of -fnew-ttp-matching.  */;
23517       else
23518 	{
23519 	  ++processing_template_decl;
23520 	  tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
23521 	  --processing_template_decl;
23522 
23523 	  if (tree a = type_uses_auto (tparm))
23524 	    {
23525 	      tparm = do_auto_deduction (tparm, arg, a, complain, adc_unify);
23526 	      if (tparm == error_mark_node)
23527 		return 1;
23528 	    }
23529 	}
23530 
23531       if (!TREE_TYPE (arg))
23532 	/* Template-parameter dependent expression.  Just accept it for now.
23533 	   It will later be processed in convert_template_argument.  */
23534 	;
23535       else if (same_type_ignoring_top_level_qualifiers_p
23536 	       (non_reference (TREE_TYPE (arg)),
23537 		non_reference (tparm)))
23538 	/* OK.  Ignore top-level quals here because a class-type template
23539 	   parameter object is const.  */;
23540       else if ((strict & UNIFY_ALLOW_INTEGER)
23541 	       && CP_INTEGRAL_TYPE_P (tparm))
23542 	/* Convert the ARG to the type of PARM; the deduced non-type
23543 	   template argument must exactly match the types of the
23544 	   corresponding parameter.  */
23545 	arg = fold (build_nop (tparm, arg));
23546       else if (uses_template_parms (tparm))
23547 	{
23548 	  /* We haven't deduced the type of this parameter yet.  */
23549 	  if (cxx_dialect >= cxx17
23550 	      /* We deduce from array bounds in try_array_deduction.  */
23551 	      && !(strict & UNIFY_ALLOW_INTEGER))
23552 	    {
23553 	      /* Deduce it from the non-type argument.  */
23554 	      tree atype = TREE_TYPE (arg);
23555 	      RECUR_AND_CHECK_FAILURE (tparms, targs,
23556 				       tparm, atype,
23557 				       UNIFY_ALLOW_NONE, explain_p);
23558 	    }
23559 	  else
23560 	    /* Try again later.  */
23561 	    return unify_success (explain_p);
23562 	}
23563       else
23564 	return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
23565 
23566       /* If ARG is a parameter pack or an expansion, we cannot unify
23567 	 against it unless PARM is also a parameter pack.  */
23568       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
23569 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
23570 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
23571 
23572       {
23573 	bool removed_attr = false;
23574 	arg = strip_typedefs_expr (arg, &removed_attr);
23575       }
23576       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
23577       return unify_success (explain_p);
23578 
23579     case PTRMEM_CST:
23580      {
23581 	/* A pointer-to-member constant can be unified only with
23582 	 another constant.  */
23583       if (TREE_CODE (arg) != PTRMEM_CST)
23584 	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
23585 
23586       /* Just unify the class member. It would be useless (and possibly
23587 	 wrong, depending on the strict flags) to unify also
23588 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
23589 	 arg refer to the same variable, even if through different
23590 	 classes. For instance:
23591 
23592 	 struct A { int x; };
23593 	 struct B : A { };
23594 
23595 	 Unification of &A::x and &B::x must succeed.  */
23596       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
23597 		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
23598      }
23599 
23600     case POINTER_TYPE:
23601       {
23602 	if (!TYPE_PTR_P (arg))
23603 	  return unify_type_mismatch (explain_p, parm, arg);
23604 
23605 	/* [temp.deduct.call]
23606 
23607 	   A can be another pointer or pointer to member type that can
23608 	   be converted to the deduced A via a qualification
23609 	   conversion (_conv.qual_).
23610 
23611 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
23612 	   This will allow for additional cv-qualification of the
23613 	   pointed-to types if appropriate.  */
23614 
23615 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
23616 	  /* The derived-to-base conversion only persists through one
23617 	     level of pointers.  */
23618 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
23619 
23620 	return unify (tparms, targs, TREE_TYPE (parm),
23621 		      TREE_TYPE (arg), strict, explain_p);
23622       }
23623 
23624     case REFERENCE_TYPE:
23625       if (!TYPE_REF_P (arg))
23626 	return unify_type_mismatch (explain_p, parm, arg);
23627       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23628 		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
23629 
23630     case ARRAY_TYPE:
23631       if (TREE_CODE (arg) != ARRAY_TYPE)
23632 	return unify_type_mismatch (explain_p, parm, arg);
23633       if ((TYPE_DOMAIN (parm) == NULL_TREE)
23634 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
23635 	return unify_type_mismatch (explain_p, parm, arg);
23636       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23637 			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
23638       if (TYPE_DOMAIN (parm) != NULL_TREE)
23639 	return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
23640 				   TYPE_DOMAIN (arg), explain_p);
23641       return unify_success (explain_p);
23642 
23643     case REAL_TYPE:
23644     case COMPLEX_TYPE:
23645     case VECTOR_TYPE:
23646     case INTEGER_TYPE:
23647     case BOOLEAN_TYPE:
23648     case ENUMERAL_TYPE:
23649     case VOID_TYPE:
23650     case NULLPTR_TYPE:
23651       if (TREE_CODE (arg) != TREE_CODE (parm))
23652 	return unify_type_mismatch (explain_p, parm, arg);
23653 
23654       /* We have already checked cv-qualification at the top of the
23655 	 function.  */
23656       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
23657 	return unify_type_mismatch (explain_p, parm, arg);
23658 
23659       /* As far as unification is concerned, this wins.	 Later checks
23660 	 will invalidate it if necessary.  */
23661       return unify_success (explain_p);
23662 
23663       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
23664       /* Type INTEGER_CST can come from ordinary constant template args.  */
23665     case INTEGER_CST:
23666       while (CONVERT_EXPR_P (arg))
23667 	arg = TREE_OPERAND (arg, 0);
23668 
23669       if (TREE_CODE (arg) != INTEGER_CST)
23670 	return unify_template_argument_mismatch (explain_p, parm, arg);
23671       return (tree_int_cst_equal (parm, arg)
23672 	      ? unify_success (explain_p)
23673 	      : unify_template_argument_mismatch (explain_p, parm, arg));
23674 
23675     case TREE_VEC:
23676       {
23677 	int i, len, argslen;
23678 	int parm_variadic_p = 0;
23679 
23680 	if (TREE_CODE (arg) != TREE_VEC)
23681 	  return unify_template_argument_mismatch (explain_p, parm, arg);
23682 
23683 	len = TREE_VEC_LENGTH (parm);
23684 	argslen = TREE_VEC_LENGTH (arg);
23685 
23686 	/* Check for pack expansions in the parameters.  */
23687 	for (i = 0; i < len; ++i)
23688 	  {
23689 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
23690 	      {
23691 		if (i == len - 1)
23692 		  /* We can unify against something with a trailing
23693 		     parameter pack.  */
23694 		  parm_variadic_p = 1;
23695 		else
23696 		  /* [temp.deduct.type]/9: If the template argument list of
23697 		     P contains a pack expansion that is not the last
23698 		     template argument, the entire template argument list
23699 		     is a non-deduced context.  */
23700 		  return unify_success (explain_p);
23701 	      }
23702 	  }
23703 
23704         /* If we don't have enough arguments to satisfy the parameters
23705            (not counting the pack expression at the end), or we have
23706            too many arguments for a parameter list that doesn't end in
23707            a pack expression, we can't unify.  */
23708 	if (parm_variadic_p
23709 	    ? argslen < len - parm_variadic_p
23710 	    : argslen != len)
23711 	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
23712 
23713 	/* Unify all of the parameters that precede the (optional)
23714 	   pack expression.  */
23715 	for (i = 0; i < len - parm_variadic_p; ++i)
23716 	  {
23717 	    RECUR_AND_CHECK_FAILURE (tparms, targs,
23718 				     TREE_VEC_ELT (parm, i),
23719 				     TREE_VEC_ELT (arg, i),
23720 				     UNIFY_ALLOW_NONE, explain_p);
23721 	  }
23722 	if (parm_variadic_p)
23723 	  return unify_pack_expansion (tparms, targs, parm, arg,
23724 				       DEDUCE_EXACT,
23725 				       /*subr=*/true, explain_p);
23726 	return unify_success (explain_p);
23727       }
23728 
23729     case RECORD_TYPE:
23730     case UNION_TYPE:
23731       if (TREE_CODE (arg) != TREE_CODE (parm))
23732 	return unify_type_mismatch (explain_p, parm, arg);
23733 
23734       if (TYPE_PTRMEMFUNC_P (parm))
23735 	{
23736 	  if (!TYPE_PTRMEMFUNC_P (arg))
23737 	    return unify_type_mismatch (explain_p, parm, arg);
23738 
23739 	  return unify (tparms, targs,
23740 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
23741 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
23742 			strict, explain_p);
23743 	}
23744       else if (TYPE_PTRMEMFUNC_P (arg))
23745 	return unify_type_mismatch (explain_p, parm, arg);
23746 
23747       if (CLASSTYPE_TEMPLATE_INFO (parm))
23748 	{
23749 	  tree t = NULL_TREE;
23750 
23751 	  if (strict_in & UNIFY_ALLOW_DERIVED)
23752 	    {
23753 	      /* First, we try to unify the PARM and ARG directly.  */
23754 	      t = try_class_unification (tparms, targs,
23755 					 parm, arg, explain_p);
23756 
23757 	      if (!t)
23758 		{
23759 		  /* Fallback to the special case allowed in
23760 		     [temp.deduct.call]:
23761 
23762 		       If P is a class, and P has the form
23763 		       template-id, then A can be a derived class of
23764 		       the deduced A.  Likewise, if P is a pointer to
23765 		       a class of the form template-id, A can be a
23766 		       pointer to a derived class pointed to by the
23767 		       deduced A.  */
23768 		  enum template_base_result r;
23769 		  r = get_template_base (tparms, targs, parm, arg,
23770 					 explain_p, &t);
23771 
23772 		  if (!t)
23773 		    {
23774 		      /* Don't give the derived diagnostic if we're
23775 			 already dealing with the same template.  */
23776 		      bool same_template
23777 			= (CLASSTYPE_TEMPLATE_INFO (arg)
23778 			   && (CLASSTYPE_TI_TEMPLATE (parm)
23779 			       == CLASSTYPE_TI_TEMPLATE (arg)));
23780 		      return unify_no_common_base (explain_p && !same_template,
23781 						   r, parm, arg);
23782 		    }
23783 		}
23784 	    }
23785 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
23786 		   && (CLASSTYPE_TI_TEMPLATE (parm)
23787 		       == CLASSTYPE_TI_TEMPLATE (arg)))
23788 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
23789 	       Then, we should unify `int' and `U'.  */
23790 	    t = arg;
23791 	  else
23792 	    /* There's no chance of unification succeeding.  */
23793 	    return unify_type_mismatch (explain_p, parm, arg);
23794 
23795 	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
23796 			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
23797 	}
23798       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
23799 	return unify_type_mismatch (explain_p, parm, arg);
23800       return unify_success (explain_p);
23801 
23802     case METHOD_TYPE:
23803     case FUNCTION_TYPE:
23804       {
23805 	unsigned int nargs;
23806 	tree *args;
23807 	tree a;
23808 	unsigned int i;
23809 
23810 	if (TREE_CODE (arg) != TREE_CODE (parm))
23811 	  return unify_type_mismatch (explain_p, parm, arg);
23812 
23813 	/* CV qualifications for methods can never be deduced, they must
23814 	   match exactly.  We need to check them explicitly here,
23815 	   because type_unification_real treats them as any other
23816 	   cv-qualified parameter.  */
23817 	if (TREE_CODE (parm) == METHOD_TYPE
23818 	    && (!check_cv_quals_for_unify
23819 		(UNIFY_ALLOW_NONE,
23820 		 class_of_this_parm (arg),
23821 		 class_of_this_parm (parm))))
23822 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
23823 	if (TREE_CODE (arg) == FUNCTION_TYPE
23824 	    && type_memfn_quals (parm) != type_memfn_quals (arg))
23825 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
23826 	if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
23827 	  return unify_type_mismatch (explain_p, parm, arg);
23828 
23829 	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
23830 				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
23831 
23832 	nargs = list_length (TYPE_ARG_TYPES (arg));
23833 	args = XALLOCAVEC (tree, nargs);
23834 	for (a = TYPE_ARG_TYPES (arg), i = 0;
23835 	     a != NULL_TREE && a != void_list_node;
23836 	     a = TREE_CHAIN (a), ++i)
23837 	  args[i] = TREE_VALUE (a);
23838 	nargs = i;
23839 
23840 	if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
23841 				   args, nargs, 1, DEDUCE_EXACT,
23842 				   NULL, explain_p))
23843 	  return 1;
23844 
23845 	if (flag_noexcept_type)
23846 	  {
23847 	    tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
23848 	    tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
23849 	    if (pspec == NULL_TREE) pspec = noexcept_false_spec;
23850 	    if (aspec == NULL_TREE) aspec = noexcept_false_spec;
23851 	    if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
23852 		&& uses_template_parms (TREE_PURPOSE (pspec)))
23853 	      RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
23854 				       TREE_PURPOSE (aspec),
23855 				       UNIFY_ALLOW_NONE, explain_p);
23856 	    else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
23857 	      return unify_type_mismatch (explain_p, parm, arg);
23858 	  }
23859 
23860 	return 0;
23861       }
23862 
23863     case OFFSET_TYPE:
23864       /* Unify a pointer to member with a pointer to member function, which
23865 	 deduces the type of the member as a function type. */
23866       if (TYPE_PTRMEMFUNC_P (arg))
23867 	{
23868 	  /* Check top-level cv qualifiers */
23869 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
23870 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
23871 
23872 	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
23873 				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
23874 				   UNIFY_ALLOW_NONE, explain_p);
23875 
23876 	  /* Determine the type of the function we are unifying against. */
23877 	  tree fntype = static_fn_type (arg);
23878 
23879 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
23880 	}
23881 
23882       if (TREE_CODE (arg) != OFFSET_TYPE)
23883 	return unify_type_mismatch (explain_p, parm, arg);
23884       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
23885 			       TYPE_OFFSET_BASETYPE (arg),
23886 			       UNIFY_ALLOW_NONE, explain_p);
23887       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
23888 		    strict, explain_p);
23889 
23890     case CONST_DECL:
23891       if (DECL_TEMPLATE_PARM_P (parm))
23892 	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
23893       if (arg != scalar_constant_value (parm))
23894 	return unify_template_argument_mismatch (explain_p, parm, arg);
23895       return unify_success (explain_p);
23896 
23897     case FIELD_DECL:
23898     case TEMPLATE_DECL:
23899       /* Matched cases are handled by the ARG == PARM test above.  */
23900       return unify_template_argument_mismatch (explain_p, parm, arg);
23901 
23902     case VAR_DECL:
23903       /* We might get a variable as a non-type template argument in parm if the
23904 	 corresponding parameter is type-dependent.  Make any necessary
23905 	 adjustments based on whether arg is a reference.  */
23906       if (CONSTANT_CLASS_P (arg))
23907 	parm = fold_non_dependent_expr (parm, complain);
23908       else if (REFERENCE_REF_P (arg))
23909 	{
23910 	  tree sub = TREE_OPERAND (arg, 0);
23911 	  STRIP_NOPS (sub);
23912 	  if (TREE_CODE (sub) == ADDR_EXPR)
23913 	    arg = TREE_OPERAND (sub, 0);
23914 	}
23915       /* Now use the normal expression code to check whether they match.  */
23916       goto expr;
23917 
23918     case TYPE_ARGUMENT_PACK:
23919     case NONTYPE_ARGUMENT_PACK:
23920       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
23921 		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
23922 
23923     case TYPEOF_TYPE:
23924     case DECLTYPE_TYPE:
23925     case UNDERLYING_TYPE:
23926       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
23927 	 or UNDERLYING_TYPE nodes.  */
23928       return unify_success (explain_p);
23929 
23930     case ERROR_MARK:
23931       /* Unification fails if we hit an error node.  */
23932       return unify_invalid (explain_p);
23933 
23934     case INDIRECT_REF:
23935       if (REFERENCE_REF_P (parm))
23936 	{
23937 	  bool pexp = PACK_EXPANSION_P (arg);
23938 	  if (pexp)
23939 	    arg = PACK_EXPANSION_PATTERN (arg);
23940 	  if (REFERENCE_REF_P (arg))
23941 	    arg = TREE_OPERAND (arg, 0);
23942 	  if (pexp)
23943 	    arg = make_pack_expansion (arg, complain);
23944 	  return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
23945 			strict, explain_p);
23946 	}
23947       /* FALLTHRU */
23948 
23949     default:
23950       /* An unresolved overload is a nondeduced context.  */
23951       if (is_overloaded_fn (parm) || type_unknown_p (parm))
23952 	return unify_success (explain_p);
23953       gcc_assert (EXPR_P (parm)
23954 		  || COMPOUND_LITERAL_P (parm)
23955 		  || TREE_CODE (parm) == TRAIT_EXPR);
23956     expr:
23957       /* We must be looking at an expression.  This can happen with
23958 	 something like:
23959 
23960 	   template <int I>
23961 	   void foo(S<I>, S<I + 2>);
23962 
23963 	 or
23964 
23965 	   template<typename T>
23966 	   void foo(A<T, T{}>);
23967 
23968 	 This is a "non-deduced context":
23969 
23970 	   [deduct.type]
23971 
23972 	   The non-deduced contexts are:
23973 
23974 	   --A non-type template argument or an array bound in which
23975 	     a subexpression references a template parameter.
23976 
23977 	 In these cases, we assume deduction succeeded, but don't
23978 	 actually infer any unifications.  */
23979 
23980       if (!uses_template_parms (parm)
23981 	  && !template_args_equal (parm, arg))
23982 	return unify_expression_unequal (explain_p, parm, arg);
23983       else
23984 	return unify_success (explain_p);
23985     }
23986 }
23987 #undef RECUR_AND_CHECK_FAILURE
23988 
23989 /* Note that DECL can be defined in this translation unit, if
23990    required.  */
23991 
23992 static void
mark_definable(tree decl)23993 mark_definable (tree decl)
23994 {
23995   tree clone;
23996   DECL_NOT_REALLY_EXTERN (decl) = 1;
23997   FOR_EACH_CLONE (clone, decl)
23998     DECL_NOT_REALLY_EXTERN (clone) = 1;
23999 }
24000 
24001 /* Called if RESULT is explicitly instantiated, or is a member of an
24002    explicitly instantiated class.  */
24003 
24004 void
mark_decl_instantiated(tree result,int extern_p)24005 mark_decl_instantiated (tree result, int extern_p)
24006 {
24007   SET_DECL_EXPLICIT_INSTANTIATION (result);
24008 
24009   /* If this entity has already been written out, it's too late to
24010      make any modifications.  */
24011   if (TREE_ASM_WRITTEN (result))
24012     return;
24013 
24014   /* consteval functions are never emitted.  */
24015   if (TREE_CODE (result) == FUNCTION_DECL
24016       && DECL_IMMEDIATE_FUNCTION_P (result))
24017     return;
24018 
24019   /* For anonymous namespace we don't need to do anything.  */
24020   if (decl_anon_ns_mem_p (result))
24021     {
24022       gcc_assert (!TREE_PUBLIC (result));
24023       return;
24024     }
24025 
24026   if (TREE_CODE (result) != FUNCTION_DECL)
24027     /* The TREE_PUBLIC flag for function declarations will have been
24028        set correctly by tsubst.  */
24029     TREE_PUBLIC (result) = 1;
24030 
24031   /* This might have been set by an earlier implicit instantiation.  */
24032   DECL_COMDAT (result) = 0;
24033 
24034   if (extern_p)
24035     DECL_NOT_REALLY_EXTERN (result) = 0;
24036   else
24037     {
24038       mark_definable (result);
24039       mark_needed (result);
24040       /* Always make artificials weak.  */
24041       if (DECL_ARTIFICIAL (result) && flag_weak)
24042 	comdat_linkage (result);
24043       /* For WIN32 we also want to put explicit instantiations in
24044 	 linkonce sections.  */
24045       else if (TREE_PUBLIC (result))
24046 	maybe_make_one_only (result);
24047       if (TREE_CODE (result) == FUNCTION_DECL
24048 	  && DECL_TEMPLATE_INSTANTIATED (result))
24049 	/* If the function has already been instantiated, clear DECL_EXTERNAL,
24050 	   since start_preparsed_function wouldn't have if we had an earlier
24051 	   extern explicit instantiation.  */
24052 	DECL_EXTERNAL (result) = 0;
24053     }
24054 
24055   /* If EXTERN_P, then this function will not be emitted -- unless
24056      followed by an explicit instantiation, at which point its linkage
24057      will be adjusted.  If !EXTERN_P, then this function will be
24058      emitted here.  In neither circumstance do we want
24059      import_export_decl to adjust the linkage.  */
24060   DECL_INTERFACE_KNOWN (result) = 1;
24061 }
24062 
24063 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
24064    important template arguments.  If any are missing, we check whether
24065    they're important by using error_mark_node for substituting into any
24066    args that were used for partial ordering (the ones between ARGS and END)
24067    and seeing if it bubbles up.  */
24068 
24069 static bool
check_undeduced_parms(tree targs,tree args,tree end)24070 check_undeduced_parms (tree targs, tree args, tree end)
24071 {
24072   bool found = false;
24073   int i;
24074   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
24075     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
24076       {
24077 	found = true;
24078 	TREE_VEC_ELT (targs, i) = error_mark_node;
24079       }
24080   if (found)
24081     {
24082       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
24083       if (substed == error_mark_node)
24084 	return true;
24085     }
24086   return false;
24087 }
24088 
24089 /* Given two function templates PAT1 and PAT2, return:
24090 
24091    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
24092    -1 if PAT2 is more specialized than PAT1.
24093    0 if neither is more specialized.
24094 
24095    LEN indicates the number of parameters we should consider
24096    (defaulted parameters should not be considered).
24097 
24098    The 1998 std underspecified function template partial ordering, and
24099    DR214 addresses the issue.  We take pairs of arguments, one from
24100    each of the templates, and deduce them against each other.  One of
24101    the templates will be more specialized if all the *other*
24102    template's arguments deduce against its arguments and at least one
24103    of its arguments *does* *not* deduce against the other template's
24104    corresponding argument.  Deduction is done as for class templates.
24105    The arguments used in deduction have reference and top level cv
24106    qualifiers removed.  Iff both arguments were originally reference
24107    types *and* deduction succeeds in both directions, an lvalue reference
24108    wins against an rvalue reference and otherwise the template
24109    with the more cv-qualified argument wins for that pairing (if
24110    neither is more cv-qualified, they both are equal).  Unlike regular
24111    deduction, after all the arguments have been deduced in this way,
24112    we do *not* verify the deduced template argument values can be
24113    substituted into non-deduced contexts.
24114 
24115    The logic can be a bit confusing here, because we look at deduce1 and
24116    targs1 to see if pat2 is at least as specialized, and vice versa; if we
24117    can find template arguments for pat1 to make arg1 look like arg2, that
24118    means that arg2 is at least as specialized as arg1.  */
24119 
24120 int
more_specialized_fn(tree pat1,tree pat2,int len)24121 more_specialized_fn (tree pat1, tree pat2, int len)
24122 {
24123   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
24124   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
24125   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
24126   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
24127   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
24128   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
24129   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
24130   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
24131   tree origs1, origs2;
24132   bool lose1 = false;
24133   bool lose2 = false;
24134 
24135   /* Remove the this parameter from non-static member functions.  If
24136      one is a non-static member function and the other is not a static
24137      member function, remove the first parameter from that function
24138      also.  This situation occurs for operator functions where we
24139      locate both a member function (with this pointer) and non-member
24140      operator (with explicit first operand).  */
24141   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
24142     {
24143       len--; /* LEN is the number of significant arguments for DECL1 */
24144       args1 = TREE_CHAIN (args1);
24145       if (!DECL_STATIC_FUNCTION_P (decl2))
24146 	args2 = TREE_CHAIN (args2);
24147     }
24148   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
24149     {
24150       args2 = TREE_CHAIN (args2);
24151       if (!DECL_STATIC_FUNCTION_P (decl1))
24152 	{
24153 	  len--;
24154 	  args1 = TREE_CHAIN (args1);
24155 	}
24156     }
24157 
24158   /* If only one is a conversion operator, they are unordered.  */
24159   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
24160     return 0;
24161 
24162   /* Consider the return type for a conversion function */
24163   if (DECL_CONV_FN_P (decl1))
24164     {
24165       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
24166       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
24167       len++;
24168     }
24169 
24170   processing_template_decl++;
24171 
24172   origs1 = args1;
24173   origs2 = args2;
24174 
24175   while (len--
24176 	 /* Stop when an ellipsis is seen.  */
24177 	 && args1 != NULL_TREE && args2 != NULL_TREE)
24178     {
24179       tree arg1 = TREE_VALUE (args1);
24180       tree arg2 = TREE_VALUE (args2);
24181       int deduce1, deduce2;
24182       int quals1 = -1;
24183       int quals2 = -1;
24184       int ref1 = 0;
24185       int ref2 = 0;
24186 
24187       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
24188           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24189         {
24190           /* When both arguments are pack expansions, we need only
24191              unify the patterns themselves.  */
24192           arg1 = PACK_EXPANSION_PATTERN (arg1);
24193           arg2 = PACK_EXPANSION_PATTERN (arg2);
24194 
24195           /* This is the last comparison we need to do.  */
24196           len = 0;
24197         }
24198 
24199       /* DR 1847: If a particular P contains no template-parameters that
24200 	 participate in template argument deduction, that P is not used to
24201 	 determine the ordering.  */
24202       if (!uses_deducible_template_parms (arg1)
24203 	  && !uses_deducible_template_parms (arg2))
24204 	goto next;
24205 
24206       if (TYPE_REF_P (arg1))
24207 	{
24208 	  ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
24209 	  arg1 = TREE_TYPE (arg1);
24210 	  quals1 = cp_type_quals (arg1);
24211 	}
24212 
24213       if (TYPE_REF_P (arg2))
24214 	{
24215 	  ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
24216 	  arg2 = TREE_TYPE (arg2);
24217 	  quals2 = cp_type_quals (arg2);
24218 	}
24219 
24220       arg1 = TYPE_MAIN_VARIANT (arg1);
24221       arg2 = TYPE_MAIN_VARIANT (arg2);
24222 
24223       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
24224         {
24225           int i, len2 = remaining_arguments (args2);
24226           tree parmvec = make_tree_vec (1);
24227           tree argvec = make_tree_vec (len2);
24228           tree ta = args2;
24229 
24230           /* Setup the parameter vector, which contains only ARG1.  */
24231           TREE_VEC_ELT (parmvec, 0) = arg1;
24232 
24233           /* Setup the argument vector, which contains the remaining
24234              arguments.  */
24235           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
24236             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
24237 
24238           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
24239 					   argvec, DEDUCE_EXACT,
24240 					   /*subr=*/true, /*explain_p=*/false)
24241 		     == 0);
24242 
24243           /* We cannot deduce in the other direction, because ARG1 is
24244              a pack expansion but ARG2 is not.  */
24245           deduce2 = 0;
24246         }
24247       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24248         {
24249           int i, len1 = remaining_arguments (args1);
24250           tree parmvec = make_tree_vec (1);
24251           tree argvec = make_tree_vec (len1);
24252           tree ta = args1;
24253 
24254           /* Setup the parameter vector, which contains only ARG1.  */
24255           TREE_VEC_ELT (parmvec, 0) = arg2;
24256 
24257           /* Setup the argument vector, which contains the remaining
24258              arguments.  */
24259           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
24260             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
24261 
24262           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
24263 					   argvec, DEDUCE_EXACT,
24264 					   /*subr=*/true, /*explain_p=*/false)
24265 		     == 0);
24266 
24267           /* We cannot deduce in the other direction, because ARG2 is
24268              a pack expansion but ARG1 is not.*/
24269           deduce1 = 0;
24270         }
24271 
24272       else
24273         {
24274           /* The normal case, where neither argument is a pack
24275              expansion.  */
24276           deduce1 = (unify (tparms1, targs1, arg1, arg2,
24277 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
24278 		     == 0);
24279           deduce2 = (unify (tparms2, targs2, arg2, arg1,
24280 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
24281 		     == 0);
24282         }
24283 
24284       /* If we couldn't deduce arguments for tparms1 to make arg1 match
24285 	 arg2, then arg2 is not as specialized as arg1.  */
24286       if (!deduce1)
24287 	lose2 = true;
24288       if (!deduce2)
24289 	lose1 = true;
24290 
24291       /* "If, for a given type, deduction succeeds in both directions
24292 	 (i.e., the types are identical after the transformations above)
24293 	 and both P and A were reference types (before being replaced with
24294 	 the type referred to above):
24295 	 - if the type from the argument template was an lvalue reference and
24296 	 the type from the parameter template was not, the argument type is
24297 	 considered to be more specialized than the other; otherwise,
24298 	 - if the type from the argument template is more cv-qualified
24299 	 than the type from the parameter template (as described above),
24300 	 the argument type is considered to be more specialized than the other;
24301 	 otherwise,
24302 	 - neither type is more specialized than the other."  */
24303 
24304       if (deduce1 && deduce2)
24305 	{
24306 	  if (ref1 && ref2 && ref1 != ref2)
24307 	    {
24308 	      if (ref1 > ref2)
24309 		lose1 = true;
24310 	      else
24311 		lose2 = true;
24312 	    }
24313 	  else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
24314 	    {
24315 	      if ((quals1 & quals2) == quals2)
24316 		lose2 = true;
24317 	      if ((quals1 & quals2) == quals1)
24318 		lose1 = true;
24319 	    }
24320 	}
24321 
24322       if (lose1 && lose2)
24323 	/* We've failed to deduce something in either direction.
24324 	   These must be unordered.  */
24325 	break;
24326 
24327     next:
24328 
24329       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
24330           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
24331         /* We have already processed all of the arguments in our
24332            handing of the pack expansion type.  */
24333         len = 0;
24334 
24335       args1 = TREE_CHAIN (args1);
24336       args2 = TREE_CHAIN (args2);
24337     }
24338 
24339   /* "In most cases, all template parameters must have values in order for
24340      deduction to succeed, but for partial ordering purposes a template
24341      parameter may remain without a value provided it is not used in the
24342      types being used for partial ordering."
24343 
24344      Thus, if we are missing any of the targs1 we need to substitute into
24345      origs1, then pat2 is not as specialized as pat1.  This can happen when
24346      there is a nondeduced context.  */
24347   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
24348     lose2 = true;
24349   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
24350     lose1 = true;
24351 
24352   processing_template_decl--;
24353 
24354   /* If both deductions succeed, the partial ordering selects the more
24355      constrained template.  */
24356   /* P2113: If the corresponding template-parameters of the
24357      template-parameter-lists are not equivalent ([temp.over.link]) or if
24358      the function parameters that positionally correspond between the two
24359      templates are not of the same type, neither template is more
24360      specialized than the other.  */
24361   if (!lose1 && !lose2
24362       && comp_template_parms (DECL_TEMPLATE_PARMS (pat1),
24363 			      DECL_TEMPLATE_PARMS (pat2))
24364       && compparms (origs1, origs2))
24365     {
24366       int winner = more_constrained (decl1, decl2);
24367       if (winner > 0)
24368 	lose2 = true;
24369       else if (winner < 0)
24370 	lose1 = true;
24371     }
24372 
24373   /* All things being equal, if the next argument is a pack expansion
24374      for one function but not for the other, prefer the
24375      non-variadic function.  FIXME this is bogus; see c++/41958.  */
24376   if (lose1 == lose2
24377       && args1 && TREE_VALUE (args1)
24378       && args2 && TREE_VALUE (args2))
24379     {
24380       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
24381       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
24382     }
24383 
24384   if (lose1 == lose2)
24385     return 0;
24386   else if (!lose1)
24387     return 1;
24388   else
24389     return -1;
24390 }
24391 
24392 /* Determine which of two partial specializations of TMPL is more
24393    specialized.
24394 
24395    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
24396    to the first partial specialization.  The TREE_PURPOSE is the
24397    innermost set of template parameters for the partial
24398    specialization.  PAT2 is similar, but for the second template.
24399 
24400    Return 1 if the first partial specialization is more specialized;
24401    -1 if the second is more specialized; 0 if neither is more
24402    specialized.
24403 
24404    See [temp.class.order] for information about determining which of
24405    two templates is more specialized.  */
24406 
24407 static int
more_specialized_partial_spec(tree tmpl,tree pat1,tree pat2)24408 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
24409 {
24410   tree targs;
24411   int winner = 0;
24412   bool any_deductions = false;
24413 
24414   tree tmpl1 = TREE_VALUE (pat1);
24415   tree tmpl2 = TREE_VALUE (pat2);
24416   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
24417   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
24418 
24419   /* Just like what happens for functions, if we are ordering between
24420      different template specializations, we may encounter dependent
24421      types in the arguments, and we need our dependency check functions
24422      to behave correctly.  */
24423   ++processing_template_decl;
24424   targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
24425   if (targs)
24426     {
24427       --winner;
24428       any_deductions = true;
24429     }
24430 
24431   targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
24432   if (targs)
24433     {
24434       ++winner;
24435       any_deductions = true;
24436     }
24437   --processing_template_decl;
24438 
24439   /* If both deductions succeed, the partial ordering selects the more
24440      constrained template.  */
24441   if (!winner && any_deductions)
24442     winner = more_constrained (tmpl1, tmpl2);
24443 
24444   /* In the case of a tie where at least one of the templates
24445      has a parameter pack at the end, the template with the most
24446      non-packed parameters wins.  */
24447   if (winner == 0
24448       && any_deductions
24449       && (template_args_variadic_p (TREE_PURPOSE (pat1))
24450           || template_args_variadic_p (TREE_PURPOSE (pat2))))
24451     {
24452       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
24453       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
24454       int len1 = TREE_VEC_LENGTH (args1);
24455       int len2 = TREE_VEC_LENGTH (args2);
24456 
24457       /* We don't count the pack expansion at the end.  */
24458       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
24459         --len1;
24460       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
24461         --len2;
24462 
24463       if (len1 > len2)
24464         return 1;
24465       else if (len1 < len2)
24466         return -1;
24467     }
24468 
24469   return winner;
24470 }
24471 
24472 /* Return the template arguments that will produce the function signature
24473    DECL from the function template FN, with the explicit template
24474    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
24475    also match.  Return NULL_TREE if no satisfactory arguments could be
24476    found.  */
24477 
24478 static tree
get_bindings(tree fn,tree decl,tree explicit_args,bool check_rettype)24479 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
24480 {
24481   int ntparms = DECL_NTPARMS (fn);
24482   tree targs = make_tree_vec (ntparms);
24483   tree decl_type = TREE_TYPE (decl);
24484   tree decl_arg_types;
24485   tree *args;
24486   unsigned int nargs, ix;
24487   tree arg;
24488 
24489   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
24490 
24491   /* Never do unification on the 'this' parameter.  */
24492   decl_arg_types = skip_artificial_parms_for (decl,
24493 					      TYPE_ARG_TYPES (decl_type));
24494 
24495   nargs = list_length (decl_arg_types);
24496   args = XALLOCAVEC (tree, nargs);
24497   for (arg = decl_arg_types, ix = 0;
24498        arg != NULL_TREE && arg != void_list_node;
24499        arg = TREE_CHAIN (arg), ++ix)
24500     args[ix] = TREE_VALUE (arg);
24501 
24502   if (fn_type_unification (fn, explicit_args, targs,
24503 			   args, ix,
24504 			   (check_rettype || DECL_CONV_FN_P (fn)
24505 			    ? TREE_TYPE (decl_type) : NULL_TREE),
24506 			   DEDUCE_EXACT, LOOKUP_NORMAL, NULL,
24507 			   /*explain_p=*/false,
24508 			   /*decltype*/false)
24509       == error_mark_node)
24510     return NULL_TREE;
24511 
24512   return targs;
24513 }
24514 
24515 /* Return the innermost template arguments that, when applied to a partial
24516    specialization SPEC_TMPL of TMPL, yield the ARGS.
24517 
24518    For example, suppose we have:
24519 
24520      template <class T, class U> struct S {};
24521      template <class T> struct S<T*, int> {};
24522 
24523    Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
24524    partial specialization and the ARGS will be {double*, int}.  The resulting
24525    vector will be {double}, indicating that `T' is bound to `double'.  */
24526 
24527 static tree
get_partial_spec_bindings(tree tmpl,tree spec_tmpl,tree args)24528 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
24529 {
24530   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
24531   tree spec_args
24532     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
24533   int i, ntparms = TREE_VEC_LENGTH (tparms);
24534   tree deduced_args;
24535   tree innermost_deduced_args;
24536 
24537   innermost_deduced_args = make_tree_vec (ntparms);
24538   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
24539     {
24540       deduced_args = copy_node (args);
24541       SET_TMPL_ARGS_LEVEL (deduced_args,
24542 			   TMPL_ARGS_DEPTH (deduced_args),
24543 			   innermost_deduced_args);
24544     }
24545   else
24546     deduced_args = innermost_deduced_args;
24547 
24548   bool tried_array_deduction = (cxx_dialect < cxx17);
24549  again:
24550   if (unify (tparms, deduced_args,
24551 	     INNERMOST_TEMPLATE_ARGS (spec_args),
24552 	     INNERMOST_TEMPLATE_ARGS (args),
24553 	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
24554     return NULL_TREE;
24555 
24556   for (i =  0; i < ntparms; ++i)
24557     if (! TREE_VEC_ELT (innermost_deduced_args, i))
24558       {
24559 	if (!tried_array_deduction)
24560 	  {
24561 	    try_array_deduction (tparms, innermost_deduced_args,
24562 				 INNERMOST_TEMPLATE_ARGS (spec_args));
24563 	    tried_array_deduction = true;
24564 	    if (TREE_VEC_ELT (innermost_deduced_args, i))
24565 	      goto again;
24566 	  }
24567 	return NULL_TREE;
24568       }
24569 
24570   if (!push_tinst_level (spec_tmpl, deduced_args))
24571     {
24572       excessive_deduction_depth = true;
24573       return NULL_TREE;
24574     }
24575 
24576   /* Verify that nondeduced template arguments agree with the type
24577      obtained from argument deduction.
24578 
24579      For example:
24580 
24581        struct A { typedef int X; };
24582        template <class T, class U> struct C {};
24583        template <class T> struct C<T, typename T::X> {};
24584 
24585      Then with the instantiation `C<A, int>', we can deduce that
24586      `T' is `A' but unify () does not check whether `typename T::X'
24587      is `int'.  */
24588   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
24589 
24590   if (spec_args != error_mark_node)
24591     spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
24592 				       INNERMOST_TEMPLATE_ARGS (spec_args),
24593 				       tmpl, tf_none, false, false);
24594 
24595   pop_tinst_level ();
24596 
24597   if (spec_args == error_mark_node
24598       /* We only need to check the innermost arguments; the other
24599 	 arguments will always agree.  */
24600       || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
24601 				     INNERMOST_TEMPLATE_ARGS (args)))
24602     return NULL_TREE;
24603 
24604   /* Now that we have bindings for all of the template arguments,
24605      ensure that the arguments deduced for the template template
24606      parameters have compatible template parameter lists.  See the use
24607      of template_template_parm_bindings_ok_p in fn_type_unification
24608      for more information.  */
24609   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
24610     return NULL_TREE;
24611 
24612   return deduced_args;
24613 }
24614 
24615 // Compare two function templates T1 and T2 by deducing bindings
24616 // from one against the other. If both deductions succeed, compare
24617 // constraints to see which is more constrained.
24618 static int
more_specialized_inst(tree t1,tree t2)24619 more_specialized_inst (tree t1, tree t2)
24620 {
24621   int fate = 0;
24622   int count = 0;
24623 
24624   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
24625     {
24626       --fate;
24627       ++count;
24628     }
24629 
24630   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
24631     {
24632       ++fate;
24633       ++count;
24634     }
24635 
24636   // If both deductions succeed, then one may be more constrained.
24637   if (count == 2 && fate == 0)
24638     fate = more_constrained (t1, t2);
24639 
24640   return fate;
24641 }
24642 
24643 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
24644    Return the TREE_LIST node with the most specialized template, if
24645    any.  If there is no most specialized template, the error_mark_node
24646    is returned.
24647 
24648    Note that this function does not look at, or modify, the
24649    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
24650    returned is one of the elements of INSTANTIATIONS, callers may
24651    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
24652    and retrieve it from the value returned.  */
24653 
24654 tree
most_specialized_instantiation(tree templates)24655 most_specialized_instantiation (tree templates)
24656 {
24657   tree fn, champ;
24658 
24659   ++processing_template_decl;
24660 
24661   champ = templates;
24662   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
24663     {
24664       gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
24665       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
24666       if (fate == -1)
24667 	champ = fn;
24668       else if (!fate)
24669 	{
24670 	  /* Equally specialized, move to next function.  If there
24671 	     is no next function, nothing's most specialized.  */
24672 	  fn = TREE_CHAIN (fn);
24673 	  champ = fn;
24674 	  if (!fn)
24675 	    break;
24676 	}
24677     }
24678 
24679   if (champ)
24680     /* Now verify that champ is better than everything earlier in the
24681        instantiation list.  */
24682     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
24683       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
24684       {
24685         champ = NULL_TREE;
24686         break;
24687       }
24688     }
24689 
24690   processing_template_decl--;
24691 
24692   if (!champ)
24693     return error_mark_node;
24694 
24695   return champ;
24696 }
24697 
24698 /* If DECL is a specialization of some template, return the most
24699    general such template.  Otherwise, returns NULL_TREE.
24700 
24701    For example, given:
24702 
24703      template <class T> struct S { template <class U> void f(U); };
24704 
24705    if TMPL is `template <class U> void S<int>::f(U)' this will return
24706    the full template.  This function will not trace past partial
24707    specializations, however.  For example, given in addition:
24708 
24709      template <class T> struct S<T*> { template <class U> void f(U); };
24710 
24711    if TMPL is `template <class U> void S<int*>::f(U)' this will return
24712    `template <class T> template <class U> S<T*>::f(U)'.  */
24713 
24714 tree
most_general_template(tree decl)24715 most_general_template (tree decl)
24716 {
24717   if (TREE_CODE (decl) != TEMPLATE_DECL)
24718     {
24719       if (tree tinfo = get_template_info (decl))
24720 	decl = TI_TEMPLATE (tinfo);
24721       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
24722 	 template friend, or a FIELD_DECL for a capture pack.  */
24723       if (TREE_CODE (decl) != TEMPLATE_DECL)
24724 	return NULL_TREE;
24725     }
24726 
24727   /* Look for more and more general templates.  */
24728   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
24729     {
24730       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
24731 	 (See cp-tree.h for details.)  */
24732       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
24733 	break;
24734 
24735       if (CLASS_TYPE_P (TREE_TYPE (decl))
24736 	  && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
24737 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
24738 	break;
24739 
24740       /* Stop if we run into an explicitly specialized class template.  */
24741       if (!DECL_NAMESPACE_SCOPE_P (decl)
24742 	  && DECL_CONTEXT (decl)
24743 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
24744 	break;
24745 
24746       decl = DECL_TI_TEMPLATE (decl);
24747     }
24748 
24749   return decl;
24750 }
24751 
24752 /* Return the most specialized of the template partial specializations
24753    which can produce TARGET, a specialization of some class or variable
24754    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
24755    a TEMPLATE_DECL node corresponding to the partial specialization, while
24756    the TREE_PURPOSE is the set of template arguments that must be
24757    substituted into the template pattern in order to generate TARGET.
24758 
24759    If the choice of partial specialization is ambiguous, a diagnostic
24760    is issued, and the error_mark_node is returned.  If there are no
24761    partial specializations matching TARGET, then NULL_TREE is
24762    returned, indicating that the primary template should be used.  */
24763 
24764 tree
most_specialized_partial_spec(tree target,tsubst_flags_t complain)24765 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
24766 {
24767   tree list = NULL_TREE;
24768   tree t;
24769   tree champ;
24770   int fate;
24771   bool ambiguous_p;
24772   tree outer_args = NULL_TREE;
24773   tree tmpl, args;
24774 
24775   if (TYPE_P (target))
24776     {
24777       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
24778       tmpl = TI_TEMPLATE (tinfo);
24779       args = TI_ARGS (tinfo);
24780     }
24781   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
24782     {
24783       tmpl = TREE_OPERAND (target, 0);
24784       args = TREE_OPERAND (target, 1);
24785     }
24786   else if (VAR_P (target))
24787     {
24788       tree tinfo = DECL_TEMPLATE_INFO (target);
24789       tmpl = TI_TEMPLATE (tinfo);
24790       args = TI_ARGS (tinfo);
24791     }
24792   else
24793     gcc_unreachable ();
24794 
24795   tree main_tmpl = most_general_template (tmpl);
24796 
24797   /* For determining which partial specialization to use, only the
24798      innermost args are interesting.  */
24799   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
24800     {
24801       outer_args = strip_innermost_template_args (args, 1);
24802       args = INNERMOST_TEMPLATE_ARGS (args);
24803     }
24804 
24805   /* The caller hasn't called push_to_top_level yet, but we need
24806      get_partial_spec_bindings to be done in non-template context so that we'll
24807      fully resolve everything.  */
24808   processing_template_decl_sentinel ptds;
24809 
24810   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
24811     {
24812       const tree ospec_tmpl = TREE_VALUE (t);
24813 
24814       tree spec_tmpl;
24815       if (outer_args)
24816 	{
24817 	  /* Substitute in the template args from the enclosing class.  */
24818 	  ++processing_template_decl;
24819 	  spec_tmpl = tsubst (ospec_tmpl, outer_args, tf_none, NULL_TREE);
24820 	  --processing_template_decl;
24821 	  if (spec_tmpl == error_mark_node)
24822 	    return error_mark_node;
24823 	}
24824       else
24825 	spec_tmpl = ospec_tmpl;
24826 
24827       tree spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
24828       if (spec_args)
24829 	{
24830 	  if (outer_args)
24831 	    spec_args = add_to_template_args (outer_args, spec_args);
24832 
24833           /* Keep the candidate only if the constraints are satisfied,
24834              or if we're not compiling with concepts.  */
24835           if (!flag_concepts
24836 	      || constraints_satisfied_p (ospec_tmpl, spec_args))
24837             {
24838 	      list = tree_cons (spec_args, ospec_tmpl, list);
24839               TREE_TYPE (list) = TREE_TYPE (t);
24840             }
24841 	}
24842     }
24843 
24844   if (! list)
24845     return NULL_TREE;
24846 
24847   ambiguous_p = false;
24848   t = list;
24849   champ = t;
24850   t = TREE_CHAIN (t);
24851   for (; t; t = TREE_CHAIN (t))
24852     {
24853       fate = more_specialized_partial_spec (tmpl, champ, t);
24854       if (fate == 1)
24855 	;
24856       else
24857 	{
24858 	  if (fate == 0)
24859 	    {
24860 	      t = TREE_CHAIN (t);
24861 	      if (! t)
24862 		{
24863 		  ambiguous_p = true;
24864 		  break;
24865 		}
24866 	    }
24867 	  champ = t;
24868 	}
24869     }
24870 
24871   if (!ambiguous_p)
24872     for (t = list; t && t != champ; t = TREE_CHAIN (t))
24873       {
24874 	fate = more_specialized_partial_spec (tmpl, champ, t);
24875 	if (fate != 1)
24876 	  {
24877 	    ambiguous_p = true;
24878 	    break;
24879 	  }
24880       }
24881 
24882   if (ambiguous_p)
24883     {
24884       const char *str;
24885       char *spaces = NULL;
24886       if (!(complain & tf_error))
24887 	return error_mark_node;
24888       if (TYPE_P (target))
24889 	error ("ambiguous template instantiation for %q#T", target);
24890       else
24891 	error ("ambiguous template instantiation for %q#D", target);
24892       str = ngettext ("candidate is:", "candidates are:", list_length (list));
24893       for (t = list; t; t = TREE_CHAIN (t))
24894         {
24895 	  tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
24896           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
24897 		  "%s %#qS", spaces ? spaces : str, subst);
24898           spaces = spaces ? spaces : get_spaces (str);
24899         }
24900       free (spaces);
24901       return error_mark_node;
24902     }
24903 
24904   return champ;
24905 }
24906 
24907 /* Explicitly instantiate DECL.  */
24908 
24909 void
do_decl_instantiation(tree decl,tree storage)24910 do_decl_instantiation (tree decl, tree storage)
24911 {
24912   tree result = NULL_TREE;
24913   int extern_p = 0;
24914 
24915   if (!decl || decl == error_mark_node)
24916     /* An error occurred, for which grokdeclarator has already issued
24917        an appropriate message.  */
24918     return;
24919   else if (! DECL_LANG_SPECIFIC (decl))
24920     {
24921       error ("explicit instantiation of non-template %q#D", decl);
24922       return;
24923     }
24924   else if (DECL_DECLARED_CONCEPT_P (decl))
24925     {
24926       if (VAR_P (decl))
24927 	error ("explicit instantiation of variable concept %q#D", decl);
24928       else
24929 	error ("explicit instantiation of function concept %q#D", decl);
24930       return;
24931     }
24932 
24933   bool var_templ = (DECL_TEMPLATE_INFO (decl)
24934                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
24935 
24936   if (VAR_P (decl) && !var_templ)
24937     {
24938       /* There is an asymmetry here in the way VAR_DECLs and
24939 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
24940 	 the latter, the DECL we get back will be marked as a
24941 	 template instantiation, and the appropriate
24942 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
24943 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
24944 	 should handle VAR_DECLs as it currently handles
24945 	 FUNCTION_DECLs.  */
24946       if (!DECL_CLASS_SCOPE_P (decl))
24947 	{
24948 	  error ("%qD is not a static data member of a class template", decl);
24949 	  return;
24950 	}
24951       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
24952       if (!result || !VAR_P (result))
24953 	{
24954 	  error ("no matching template for %qD found", decl);
24955 	  return;
24956 	}
24957       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
24958 	{
24959 	  error ("type %qT for explicit instantiation %qD does not match "
24960 		 "declared type %qT", TREE_TYPE (result), decl,
24961 		 TREE_TYPE (decl));
24962 	  return;
24963 	}
24964     }
24965   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
24966     {
24967       error ("explicit instantiation of %q#D", decl);
24968       return;
24969     }
24970   else
24971     result = decl;
24972 
24973   /* Check for various error cases.  Note that if the explicit
24974      instantiation is valid the RESULT will currently be marked as an
24975      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
24976      until we get here.  */
24977 
24978   if (DECL_TEMPLATE_SPECIALIZATION (result))
24979     {
24980       /* DR 259 [temp.spec].
24981 
24982 	 Both an explicit instantiation and a declaration of an explicit
24983 	 specialization shall not appear in a program unless the explicit
24984 	 instantiation follows a declaration of the explicit specialization.
24985 
24986 	 For a given set of template parameters, if an explicit
24987 	 instantiation of a template appears after a declaration of an
24988 	 explicit specialization for that template, the explicit
24989 	 instantiation has no effect.  */
24990       return;
24991     }
24992   else if (DECL_EXPLICIT_INSTANTIATION (result))
24993     {
24994       /* [temp.spec]
24995 
24996 	 No program shall explicitly instantiate any template more
24997 	 than once.
24998 
24999 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
25000 	 the first instantiation was `extern' and the second is not,
25001 	 and EXTERN_P for the opposite case.  */
25002       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
25003 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
25004       /* If an "extern" explicit instantiation follows an ordinary
25005 	 explicit instantiation, the template is instantiated.  */
25006       if (extern_p)
25007 	return;
25008     }
25009   else if (!DECL_IMPLICIT_INSTANTIATION (result))
25010     {
25011       error ("no matching template for %qD found", result);
25012       return;
25013     }
25014   else if (!DECL_TEMPLATE_INFO (result))
25015     {
25016       permerror (input_location, "explicit instantiation of non-template %q#D", result);
25017       return;
25018     }
25019 
25020   if (storage == NULL_TREE)
25021     ;
25022   else if (storage == ridpointers[(int) RID_EXTERN])
25023     {
25024       if (cxx_dialect == cxx98)
25025 	pedwarn (input_location, OPT_Wpedantic,
25026 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
25027 		 "instantiations");
25028       extern_p = 1;
25029     }
25030   else
25031     error ("storage class %qD applied to template instantiation", storage);
25032 
25033   check_explicit_instantiation_namespace (result);
25034   mark_decl_instantiated (result, extern_p);
25035   if (! extern_p)
25036     instantiate_decl (result, /*defer_ok=*/true,
25037 		      /*expl_inst_class_mem_p=*/false);
25038 }
25039 
25040 static void
mark_class_instantiated(tree t,int extern_p)25041 mark_class_instantiated (tree t, int extern_p)
25042 {
25043   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
25044   SET_CLASSTYPE_INTERFACE_KNOWN (t);
25045   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
25046   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
25047   if (! extern_p)
25048     {
25049       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
25050       rest_of_type_compilation (t, 1);
25051     }
25052 }
25053 
25054 /* Called from do_type_instantiation through binding_table_foreach to
25055    do recursive instantiation for the type bound in ENTRY.  */
25056 static void
bt_instantiate_type_proc(binding_entry entry,void * data)25057 bt_instantiate_type_proc (binding_entry entry, void *data)
25058 {
25059   tree storage = *(tree *) data;
25060 
25061   if (MAYBE_CLASS_TYPE_P (entry->type)
25062       && CLASSTYPE_TEMPLATE_INFO (entry->type)
25063       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
25064     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
25065 }
25066 
25067 /* Perform an explicit instantiation of template class T.  STORAGE, if
25068    non-null, is the RID for extern, inline or static.  COMPLAIN is
25069    nonzero if this is called from the parser, zero if called recursively,
25070    since the standard is unclear (as detailed below).  */
25071 
25072 void
do_type_instantiation(tree t,tree storage,tsubst_flags_t complain)25073 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
25074 {
25075   int extern_p = 0;
25076   int nomem_p = 0;
25077   int static_p = 0;
25078   int previous_instantiation_extern_p = 0;
25079 
25080   if (TREE_CODE (t) == TYPE_DECL)
25081     t = TREE_TYPE (t);
25082 
25083   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
25084     {
25085       tree tmpl =
25086 	(TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
25087       if (tmpl)
25088 	error ("explicit instantiation of non-class template %qD", tmpl);
25089       else
25090 	error ("explicit instantiation of non-template type %qT", t);
25091       return;
25092     }
25093 
25094   complete_type (t);
25095 
25096   if (!COMPLETE_TYPE_P (t))
25097     {
25098       if (complain & tf_error)
25099 	error ("explicit instantiation of %q#T before definition of template",
25100 	       t);
25101       return;
25102     }
25103 
25104   if (storage != NULL_TREE)
25105     {
25106       if (storage == ridpointers[(int) RID_EXTERN])
25107 	{
25108 	  if (cxx_dialect == cxx98)
25109 	    pedwarn (input_location, OPT_Wpedantic,
25110 		     "ISO C++ 1998 forbids the use of %<extern%> on "
25111 		     "explicit instantiations");
25112 	}
25113       else
25114 	pedwarn (input_location, OPT_Wpedantic,
25115 		 "ISO C++ forbids the use of %qE"
25116 		 " on explicit instantiations", storage);
25117 
25118       if (storage == ridpointers[(int) RID_INLINE])
25119 	nomem_p = 1;
25120       else if (storage == ridpointers[(int) RID_EXTERN])
25121 	extern_p = 1;
25122       else if (storage == ridpointers[(int) RID_STATIC])
25123 	static_p = 1;
25124       else
25125 	{
25126 	  error ("storage class %qD applied to template instantiation",
25127 		 storage);
25128 	  extern_p = 0;
25129 	}
25130     }
25131 
25132   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
25133     {
25134       /* DR 259 [temp.spec].
25135 
25136 	 Both an explicit instantiation and a declaration of an explicit
25137 	 specialization shall not appear in a program unless the explicit
25138 	 instantiation follows a declaration of the explicit specialization.
25139 
25140 	 For a given set of template parameters, if an explicit
25141 	 instantiation of a template appears after a declaration of an
25142 	 explicit specialization for that template, the explicit
25143 	 instantiation has no effect.  */
25144       return;
25145     }
25146   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
25147     {
25148       /* [temp.spec]
25149 
25150 	 No program shall explicitly instantiate any template more
25151 	 than once.
25152 
25153 	 If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
25154 	 instantiation was `extern'.  If EXTERN_P then the second is.
25155 	 These cases are OK.  */
25156       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
25157 
25158       if (!previous_instantiation_extern_p && !extern_p
25159 	  && (complain & tf_error))
25160 	permerror (input_location, "duplicate explicit instantiation of %q#T", t);
25161 
25162       /* If we've already instantiated the template, just return now.  */
25163       if (!CLASSTYPE_INTERFACE_ONLY (t))
25164 	return;
25165     }
25166 
25167   check_explicit_instantiation_namespace (TYPE_NAME (t));
25168   mark_class_instantiated (t, extern_p);
25169 
25170   if (nomem_p)
25171     return;
25172 
25173   /* In contrast to implicit instantiation, where only the
25174      declarations, and not the definitions, of members are
25175      instantiated, we have here:
25176 
25177 	 [temp.explicit]
25178 
25179 	 An explicit instantiation that names a class template
25180 	 specialization is also an explicit instantiation of the same
25181 	 kind (declaration or definition) of each of its members (not
25182 	 including members inherited from base classes and members
25183 	 that are templates) that has not been previously explicitly
25184 	 specialized in the translation unit containing the explicit
25185 	 instantiation, provided that the associated constraints, if
25186 	 any, of that member are satisfied by the template arguments
25187 	 of the explicit instantiation.  */
25188   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
25189     if ((VAR_P (fld)
25190 	 || (TREE_CODE (fld) == FUNCTION_DECL
25191 	     && !static_p
25192 	     && user_provided_p (fld)))
25193 	&& DECL_TEMPLATE_INSTANTIATION (fld)
25194 	&& constraints_satisfied_p (fld))
25195       {
25196 	mark_decl_instantiated (fld, extern_p);
25197 	if (! extern_p)
25198 	  instantiate_decl (fld, /*defer_ok=*/true,
25199 			    /*expl_inst_class_mem_p=*/true);
25200       }
25201 
25202   if (CLASSTYPE_NESTED_UTDS (t))
25203     binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
25204 			   bt_instantiate_type_proc, &storage);
25205 }
25206 
25207 /* Given a function DECL, which is a specialization of TMPL, modify
25208    DECL to be a re-instantiation of TMPL with the same template
25209    arguments.  TMPL should be the template into which tsubst'ing
25210    should occur for DECL, not the most general template.
25211 
25212    One reason for doing this is a scenario like this:
25213 
25214      template <class T>
25215      void f(const T&, int i);
25216 
25217      void g() { f(3, 7); }
25218 
25219      template <class T>
25220      void f(const T& t, const int i) { }
25221 
25222    Note that when the template is first instantiated, with
25223    instantiate_template, the resulting DECL will have no name for the
25224    first parameter, and the wrong type for the second.  So, when we go
25225    to instantiate the DECL, we regenerate it.  */
25226 
25227 static void
regenerate_decl_from_template(tree decl,tree tmpl,tree args)25228 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
25229 {
25230   /* The arguments used to instantiate DECL, from the most general
25231      template.  */
25232   tree code_pattern;
25233 
25234   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
25235 
25236   /* Make sure that we can see identifiers, and compute access
25237      correctly.  */
25238   push_access_scope (decl);
25239 
25240   if (TREE_CODE (decl) == FUNCTION_DECL)
25241     {
25242       tree decl_parm;
25243       tree pattern_parm;
25244       tree specs;
25245       int args_depth;
25246       int parms_depth;
25247 
25248       args_depth = TMPL_ARGS_DEPTH (args);
25249       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
25250       if (args_depth > parms_depth)
25251 	args = get_innermost_template_args (args, parms_depth);
25252 
25253       /* Instantiate a dynamic exception-specification.  noexcept will be
25254 	 handled below.  */
25255       if (tree raises = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (code_pattern)))
25256 	if (TREE_VALUE (raises))
25257 	  {
25258 	    specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
25259 						    args, tf_error, NULL_TREE,
25260 						    /*defer_ok*/false);
25261 	    if (specs && specs != error_mark_node)
25262 	      TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
25263 							  specs);
25264 	  }
25265 
25266       /* Merge parameter declarations.  */
25267       decl_parm = skip_artificial_parms_for (decl,
25268 					     DECL_ARGUMENTS (decl));
25269       pattern_parm
25270 	= skip_artificial_parms_for (code_pattern,
25271 				     DECL_ARGUMENTS (code_pattern));
25272       while (decl_parm && !DECL_PACK_P (pattern_parm))
25273 	{
25274 	  tree parm_type;
25275 	  tree attributes;
25276 
25277 	  if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
25278 	    DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
25279 	  parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
25280 			      NULL_TREE);
25281 	  parm_type = type_decays_to (parm_type);
25282 	  if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
25283 	    TREE_TYPE (decl_parm) = parm_type;
25284 	  attributes = DECL_ATTRIBUTES (pattern_parm);
25285 	  if (DECL_ATTRIBUTES (decl_parm) != attributes)
25286 	    {
25287 	      DECL_ATTRIBUTES (decl_parm) = attributes;
25288 	      cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
25289 	    }
25290 	  decl_parm = DECL_CHAIN (decl_parm);
25291 	  pattern_parm = DECL_CHAIN (pattern_parm);
25292 	}
25293       /* Merge any parameters that match with the function parameter
25294          pack.  */
25295       if (pattern_parm && DECL_PACK_P (pattern_parm))
25296         {
25297           int i, len;
25298           tree expanded_types;
25299           /* Expand the TYPE_PACK_EXPANSION that provides the types for
25300              the parameters in this function parameter pack.  */
25301           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
25302                                                  args, tf_error, NULL_TREE);
25303           len = TREE_VEC_LENGTH (expanded_types);
25304           for (i = 0; i < len; i++)
25305             {
25306               tree parm_type;
25307               tree attributes;
25308 
25309               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
25310                 /* Rename the parameter to include the index.  */
25311                 DECL_NAME (decl_parm) =
25312                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
25313               parm_type = TREE_VEC_ELT (expanded_types, i);
25314               parm_type = type_decays_to (parm_type);
25315               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
25316                 TREE_TYPE (decl_parm) = parm_type;
25317               attributes = DECL_ATTRIBUTES (pattern_parm);
25318               if (DECL_ATTRIBUTES (decl_parm) != attributes)
25319                 {
25320                   DECL_ATTRIBUTES (decl_parm) = attributes;
25321                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
25322                 }
25323               decl_parm = DECL_CHAIN (decl_parm);
25324             }
25325         }
25326       /* Merge additional specifiers from the CODE_PATTERN.  */
25327       if (DECL_DECLARED_INLINE_P (code_pattern)
25328 	  && !DECL_DECLARED_INLINE_P (decl))
25329 	DECL_DECLARED_INLINE_P (decl) = 1;
25330 
25331       maybe_instantiate_noexcept (decl, tf_error);
25332     }
25333   else if (VAR_P (decl))
25334     {
25335       start_lambda_scope (decl);
25336       DECL_INITIAL (decl) =
25337 	tsubst_init (DECL_INITIAL (code_pattern), decl, args,
25338 		     tf_error, DECL_TI_TEMPLATE (decl));
25339       finish_lambda_scope ();
25340       if (VAR_HAD_UNKNOWN_BOUND (decl))
25341 	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
25342 				   tf_error, DECL_TI_TEMPLATE (decl));
25343     }
25344   else
25345     gcc_unreachable ();
25346 
25347   pop_access_scope (decl);
25348 }
25349 
25350 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
25351    substituted to get DECL.  */
25352 
25353 tree
template_for_substitution(tree decl)25354 template_for_substitution (tree decl)
25355 {
25356   tree tmpl = DECL_TI_TEMPLATE (decl);
25357 
25358   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
25359      for the instantiation.  This is not always the most general
25360      template.  Consider, for example:
25361 
25362 	template <class T>
25363 	struct S { template <class U> void f();
25364 		   template <> void f<int>(); };
25365 
25366      and an instantiation of S<double>::f<int>.  We want TD to be the
25367      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
25368   while (/* An instantiation cannot have a definition, so we need a
25369 	    more general template.  */
25370 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
25371 	   /* We must also deal with friend templates.  Given:
25372 
25373 		template <class T> struct S {
25374 		  template <class U> friend void f() {};
25375 		};
25376 
25377 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
25378 	      so far as the language is concerned, but that's still
25379 	      where we get the pattern for the instantiation from.  On
25380 	      other hand, if the definition comes outside the class, say:
25381 
25382 		template <class T> struct S {
25383 		  template <class U> friend void f();
25384 		};
25385 		template <class U> friend void f() {}
25386 
25387 	      we don't need to look any further.  That's what the check for
25388 	      DECL_INITIAL is for.  */
25389 	  || (TREE_CODE (decl) == FUNCTION_DECL
25390 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
25391 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
25392     {
25393       /* The present template, TD, should not be a definition.  If it
25394 	 were a definition, we should be using it!  Note that we
25395 	 cannot restructure the loop to just keep going until we find
25396 	 a template with a definition, since that might go too far if
25397 	 a specialization was declared, but not defined.  */
25398 
25399       /* Fetch the more general template.  */
25400       tmpl = DECL_TI_TEMPLATE (tmpl);
25401     }
25402 
25403   return tmpl;
25404 }
25405 
25406 /* Returns true if we need to instantiate this template instance even if we
25407    know we aren't going to emit it.  */
25408 
25409 bool
always_instantiate_p(tree decl)25410 always_instantiate_p (tree decl)
25411 {
25412   /* We always instantiate inline functions so that we can inline them.  An
25413      explicit instantiation declaration prohibits implicit instantiation of
25414      non-inline functions.  With high levels of optimization, we would
25415      normally inline non-inline functions -- but we're not allowed to do
25416      that for "extern template" functions.  Therefore, we check
25417      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
25418   return ((TREE_CODE (decl) == FUNCTION_DECL
25419 	   && (DECL_DECLARED_INLINE_P (decl)
25420 	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
25421 	  /* And we need to instantiate static data members so that
25422 	     their initializers are available in integral constant
25423 	     expressions.  */
25424 	  || (VAR_P (decl)
25425 	      && decl_maybe_constant_var_p (decl)));
25426 }
25427 
25428 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
25429    instantiate it now, modifying TREE_TYPE (fn).  Returns false on
25430    error, true otherwise.  */
25431 
25432 bool
maybe_instantiate_noexcept(tree fn,tsubst_flags_t complain)25433 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
25434 {
25435   tree fntype, spec, noex, clone;
25436 
25437   if (fn == error_mark_node)
25438     return false;
25439 
25440   /* Don't instantiate a noexcept-specification from template context.  */
25441   if (processing_template_decl
25442       && (!flag_noexcept_type || type_dependent_expression_p (fn)))
25443     return true;
25444 
25445   if (DECL_MAYBE_DELETED (fn))
25446     {
25447       if (fn == current_function_decl)
25448 	/* We're in start_preparsed_function, keep going.  */
25449 	return true;
25450 
25451       ++function_depth;
25452       synthesize_method (fn);
25453       --function_depth;
25454       return !DECL_MAYBE_DELETED (fn);
25455     }
25456 
25457   if (DECL_CLONED_FUNCTION_P (fn))
25458     fn = DECL_CLONED_FUNCTION (fn);
25459 
25460   tree orig_fn = NULL_TREE;
25461   /* For a member friend template we can get a TEMPLATE_DECL.  Let's use
25462      its FUNCTION_DECL for the rest of this function -- push_access_scope
25463      doesn't accept TEMPLATE_DECLs.  */
25464   if (DECL_FUNCTION_TEMPLATE_P (fn))
25465     {
25466       orig_fn = fn;
25467       fn = DECL_TEMPLATE_RESULT (fn);
25468     }
25469 
25470   fntype = TREE_TYPE (fn);
25471   spec = TYPE_RAISES_EXCEPTIONS (fntype);
25472 
25473   if (!spec || !TREE_PURPOSE (spec))
25474     return true;
25475 
25476   noex = TREE_PURPOSE (spec);
25477 
25478   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
25479     {
25480       static hash_set<tree>* fns = new hash_set<tree>;
25481       bool added = false;
25482       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
25483 	{
25484 	  spec = get_defaulted_eh_spec (fn, complain);
25485 	  if (spec == error_mark_node)
25486 	    /* This might have failed because of an unparsed DMI, so
25487 	       let's try again later.  */
25488 	    return false;
25489 	}
25490       else if (!(added = !fns->add (fn)))
25491 	{
25492 	  /* If hash_set::add returns true, the element was already there.  */
25493 	  location_t loc = cp_expr_loc_or_loc (DEFERRED_NOEXCEPT_PATTERN (noex),
25494 					    DECL_SOURCE_LOCATION (fn));
25495 	  error_at (loc,
25496 		    "exception specification of %qD depends on itself",
25497 		    fn);
25498 	  spec = noexcept_false_spec;
25499 	}
25500       else if (push_tinst_level (fn))
25501 	{
25502 	  push_to_top_level ();
25503 	  push_access_scope (fn);
25504 	  push_deferring_access_checks (dk_no_deferred);
25505 	  input_location = DECL_SOURCE_LOCATION (fn);
25506 
25507 	  /* If needed, set current_class_ptr for the benefit of
25508 	     tsubst_copy/PARM_DECL.  */
25509 	  tree tdecl = DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (fn));
25510 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (tdecl))
25511 	    {
25512 	      tree this_parm = DECL_ARGUMENTS (tdecl);
25513 	      current_class_ptr = NULL_TREE;
25514 	      current_class_ref = cp_build_fold_indirect_ref (this_parm);
25515 	      current_class_ptr = this_parm;
25516 	    }
25517 
25518 	  /* If this function is represented by a TEMPLATE_DECL, then
25519 	     the deferred noexcept-specification might still contain
25520 	     dependent types, even after substitution.  And we need the
25521 	     dependency check functions to work in build_noexcept_spec.  */
25522 	  if (orig_fn)
25523 	    ++processing_template_decl;
25524 
25525 	  /* Do deferred instantiation of the noexcept-specifier.  */
25526 	  noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
25527 					DEFERRED_NOEXCEPT_ARGS (noex),
25528 					tf_warning_or_error, fn,
25529 					/*function_p=*/false,
25530 					/*i_c_e_p=*/true);
25531 
25532 	  /* Build up the noexcept-specification.  */
25533 	  spec = build_noexcept_spec (noex, tf_warning_or_error);
25534 
25535 	  if (orig_fn)
25536 	    --processing_template_decl;
25537 
25538 	  pop_deferring_access_checks ();
25539 	  pop_access_scope (fn);
25540 	  pop_tinst_level ();
25541 	  pop_from_top_level ();
25542 	}
25543       else
25544 	spec = noexcept_false_spec;
25545 
25546       if (added)
25547 	fns->remove (fn);
25548 
25549       if (spec == error_mark_node)
25550 	{
25551 	  /* This failed with a hard error, so let's go with false.  */
25552 	  gcc_assert (seen_error ());
25553 	  spec = noexcept_false_spec;
25554 	}
25555 
25556       TREE_TYPE (fn) = build_exception_variant (fntype, spec);
25557       if (orig_fn)
25558 	TREE_TYPE (orig_fn) = TREE_TYPE (fn);
25559     }
25560 
25561   FOR_EACH_CLONE (clone, fn)
25562     {
25563       if (TREE_TYPE (clone) == fntype)
25564 	TREE_TYPE (clone) = TREE_TYPE (fn);
25565       else
25566 	TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
25567     }
25568 
25569   return true;
25570 }
25571 
25572 /* We're starting to process the function INST, an instantiation of PATTERN;
25573    add their parameters to local_specializations.  */
25574 
25575 static void
register_parameter_specializations(tree pattern,tree inst)25576 register_parameter_specializations (tree pattern, tree inst)
25577 {
25578   tree tmpl_parm = DECL_ARGUMENTS (pattern);
25579   tree spec_parm = DECL_ARGUMENTS (inst);
25580   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
25581     {
25582       register_local_specialization (spec_parm, tmpl_parm);
25583       spec_parm = skip_artificial_parms_for (inst, spec_parm);
25584       tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
25585     }
25586   for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
25587     {
25588       if (!DECL_PACK_P (tmpl_parm))
25589 	{
25590 	  register_local_specialization (spec_parm, tmpl_parm);
25591 	  spec_parm = DECL_CHAIN (spec_parm);
25592 	}
25593       else
25594 	{
25595 	  /* Register the (value) argument pack as a specialization of
25596 	     TMPL_PARM, then move on.  */
25597 	  tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
25598 	  register_local_specialization (argpack, tmpl_parm);
25599 	}
25600     }
25601   gcc_assert (!spec_parm);
25602 }
25603 
25604 /* Produce the definition of D, a _DECL generated from a template.  If
25605    DEFER_OK is true, then we don't have to actually do the
25606    instantiation now; we just have to do it sometime.  Normally it is
25607    an error if this is an explicit instantiation but D is undefined.
25608    EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
25609    instantiated class template.  */
25610 
25611 tree
instantiate_decl(tree d,bool defer_ok,bool expl_inst_class_mem_p)25612 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
25613 {
25614   tree tmpl = DECL_TI_TEMPLATE (d);
25615   tree gen_args;
25616   tree args;
25617   tree td;
25618   tree code_pattern;
25619   tree spec;
25620   tree gen_tmpl;
25621   bool pattern_defined;
25622   location_t saved_loc = input_location;
25623   int saved_unevaluated_operand = cp_unevaluated_operand;
25624   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
25625   bool external_p;
25626   bool deleted_p;
25627 
25628   /* This function should only be used to instantiate templates for
25629      functions and static member variables.  */
25630   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
25631 
25632   /* A concept is never instantiated. */
25633   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
25634 
25635   /* Variables are never deferred; if instantiation is required, they
25636      are instantiated right away.  That allows for better code in the
25637      case that an expression refers to the value of the variable --
25638      if the variable has a constant value the referring expression can
25639      take advantage of that fact.  */
25640   if (VAR_P (d))
25641     defer_ok = false;
25642 
25643   /* Don't instantiate cloned functions.  Instead, instantiate the
25644      functions they cloned.  */
25645   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
25646     d = DECL_CLONED_FUNCTION (d);
25647 
25648   if (DECL_TEMPLATE_INSTANTIATED (d)
25649       || (TREE_CODE (d) == FUNCTION_DECL
25650 	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
25651       || DECL_TEMPLATE_SPECIALIZATION (d))
25652     /* D has already been instantiated or explicitly specialized, so
25653        there's nothing for us to do here.
25654 
25655        It might seem reasonable to check whether or not D is an explicit
25656        instantiation, and, if so, stop here.  But when an explicit
25657        instantiation is deferred until the end of the compilation,
25658        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
25659        the instantiation.  */
25660     return d;
25661 
25662   /* Check to see whether we know that this template will be
25663      instantiated in some other file, as with "extern template"
25664      extension.  */
25665   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
25666 
25667   /* In general, we do not instantiate such templates.  */
25668   if (external_p && !always_instantiate_p (d))
25669     return d;
25670 
25671   gen_tmpl = most_general_template (tmpl);
25672   gen_args = DECL_TI_ARGS (d);
25673 
25674   if (tmpl != gen_tmpl)
25675     /* We should already have the extra args.  */
25676     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
25677 		== TMPL_ARGS_DEPTH (gen_args));
25678   /* And what's in the hash table should match D.  */
25679   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
25680 	      || spec == NULL_TREE);
25681 
25682   /* This needs to happen before any tsubsting.  */
25683   if (! push_tinst_level (d))
25684     return d;
25685 
25686   timevar_push (TV_TEMPLATE_INST);
25687 
25688   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
25689      for the instantiation.  */
25690   td = template_for_substitution (d);
25691   args = gen_args;
25692 
25693   if (VAR_P (d))
25694     {
25695       /* Look up an explicit specialization, if any.  */
25696       tree tid = lookup_template_variable (gen_tmpl, gen_args);
25697       tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
25698       if (elt && elt != error_mark_node)
25699 	{
25700 	  td = TREE_VALUE (elt);
25701 	  args = TREE_PURPOSE (elt);
25702 	}
25703     }
25704 
25705   code_pattern = DECL_TEMPLATE_RESULT (td);
25706 
25707   /* We should never be trying to instantiate a member of a class
25708      template or partial specialization.  */
25709   gcc_assert (d != code_pattern);
25710 
25711   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
25712       || DECL_TEMPLATE_SPECIALIZATION (td))
25713     /* In the case of a friend template whose definition is provided
25714        outside the class, we may have too many arguments.  Drop the
25715        ones we don't need.  The same is true for specializations.  */
25716     args = get_innermost_template_args
25717       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
25718 
25719   if (TREE_CODE (d) == FUNCTION_DECL)
25720     {
25721       deleted_p = DECL_DELETED_FN (code_pattern);
25722       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
25723 			  && DECL_INITIAL (code_pattern) != error_mark_node)
25724 			 || DECL_DEFAULTED_FN (code_pattern)
25725 			 || deleted_p);
25726     }
25727   else
25728     {
25729       deleted_p = false;
25730       if (DECL_CLASS_SCOPE_P (code_pattern))
25731 	pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
25732       else
25733 	pattern_defined = ! DECL_EXTERNAL (code_pattern);
25734     }
25735 
25736   /* We may be in the middle of deferred access check.  Disable it now.  */
25737   push_deferring_access_checks (dk_no_deferred);
25738 
25739   /* Unless an explicit instantiation directive has already determined
25740      the linkage of D, remember that a definition is available for
25741      this entity.  */
25742   if (pattern_defined
25743       && !DECL_INTERFACE_KNOWN (d)
25744       && !DECL_NOT_REALLY_EXTERN (d))
25745     mark_definable (d);
25746 
25747   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
25748   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
25749   input_location = DECL_SOURCE_LOCATION (d);
25750 
25751   /* If D is a member of an explicitly instantiated class template,
25752      and no definition is available, treat it like an implicit
25753      instantiation.  */
25754   if (!pattern_defined && expl_inst_class_mem_p
25755       && DECL_EXPLICIT_INSTANTIATION (d))
25756     {
25757       /* Leave linkage flags alone on instantiations with anonymous
25758 	 visibility.  */
25759       if (TREE_PUBLIC (d))
25760 	{
25761 	  DECL_NOT_REALLY_EXTERN (d) = 0;
25762 	  DECL_INTERFACE_KNOWN (d) = 0;
25763 	}
25764       SET_DECL_IMPLICIT_INSTANTIATION (d);
25765     }
25766 
25767   /* Defer all other templates, unless we have been explicitly
25768      forbidden from doing so.  */
25769   if (/* If there is no definition, we cannot instantiate the
25770 	 template.  */
25771       ! pattern_defined
25772       /* If it's OK to postpone instantiation, do so.  */
25773       || defer_ok
25774       /* If this is a static data member that will be defined
25775 	 elsewhere, we don't want to instantiate the entire data
25776 	 member, but we do want to instantiate the initializer so that
25777 	 we can substitute that elsewhere.  */
25778       || (external_p && VAR_P (d))
25779       /* Handle here a deleted function too, avoid generating
25780 	 its body (c++/61080).  */
25781       || deleted_p)
25782     {
25783       /* The definition of the static data member is now required so
25784 	 we must substitute the initializer.  */
25785       if (VAR_P (d)
25786 	  && !DECL_INITIAL (d)
25787 	  && DECL_INITIAL (code_pattern))
25788 	{
25789 	  tree ns;
25790 	  tree init;
25791 	  bool const_init = false;
25792 	  bool enter_context = DECL_CLASS_SCOPE_P (d);
25793 
25794 	  ns = decl_namespace_context (d);
25795 	  push_nested_namespace (ns);
25796 	  if (enter_context)
25797 	    push_nested_class (DECL_CONTEXT (d));
25798 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
25799 			      args,
25800 			      tf_warning_or_error, NULL_TREE,
25801 			      /*integral_constant_expression_p=*/false);
25802 	  /* If instantiating the initializer involved instantiating this
25803 	     again, don't call cp_finish_decl twice.  */
25804 	  if (!DECL_INITIAL (d))
25805 	    {
25806 	      /* Make sure the initializer is still constant, in case of
25807 		 circular dependency (template/instantiate6.C). */
25808 	      const_init
25809 		= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
25810 	      cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
25811 			      /*asmspec_tree=*/NULL_TREE,
25812 			      LOOKUP_ONLYCONVERTING);
25813 	    }
25814 	  if (enter_context)
25815 	    pop_nested_class ();
25816 	  pop_nested_namespace (ns);
25817 	}
25818 
25819       /* We restore the source position here because it's used by
25820 	 add_pending_template.  */
25821       input_location = saved_loc;
25822 
25823       if (at_eof && !pattern_defined
25824 	  && DECL_EXPLICIT_INSTANTIATION (d)
25825 	  && DECL_NOT_REALLY_EXTERN (d))
25826 	/* [temp.explicit]
25827 
25828 	   The definition of a non-exported function template, a
25829 	   non-exported member function template, or a non-exported
25830 	   member function or static data member of a class template
25831 	   shall be present in every translation unit in which it is
25832 	   explicitly instantiated.  */
25833 	permerror (input_location,  "explicit instantiation of %qD "
25834 		   "but no definition available", d);
25835 
25836       /* If we're in unevaluated context, we just wanted to get the
25837 	 constant value; this isn't an odr use, so don't queue
25838 	 a full instantiation.  */
25839       if (cp_unevaluated_operand != 0)
25840 	goto out;
25841       /* ??? Historically, we have instantiated inline functions, even
25842 	 when marked as "extern template".  */
25843       if (!(external_p && VAR_P (d)))
25844 	add_pending_template (d);
25845       goto out;
25846     }
25847 
25848   bool push_to_top, nested;
25849   tree fn_context;
25850   fn_context = decl_function_context (d);
25851   if (LAMBDA_FUNCTION_P (d))
25852     /* tsubst_lambda_expr resolved any references to enclosing functions.  */
25853     fn_context = NULL_TREE;
25854   nested = current_function_decl != NULL_TREE;
25855   push_to_top = !(nested && fn_context == current_function_decl);
25856 
25857   vec<tree> omp_privatization_save;
25858   if (nested)
25859     save_omp_privatization_clauses (omp_privatization_save);
25860 
25861   if (push_to_top)
25862     push_to_top_level ();
25863   else
25864     {
25865       gcc_assert (!processing_template_decl);
25866       push_function_context ();
25867       cp_unevaluated_operand = 0;
25868       c_inhibit_evaluation_warnings = 0;
25869     }
25870 
25871   if (VAR_P (d))
25872     {
25873       /* The variable might be a lambda's extra scope, and that
25874 	 lambda's visibility depends on D's.  */
25875       maybe_commonize_var (d);
25876       determine_visibility (d);
25877     }
25878 
25879   /* Mark D as instantiated so that recursive calls to
25880      instantiate_decl do not try to instantiate it again.  */
25881   DECL_TEMPLATE_INSTANTIATED (d) = 1;
25882 
25883   /* Regenerate the declaration in case the template has been modified
25884      by a subsequent redeclaration.  */
25885   regenerate_decl_from_template (d, td, args);
25886 
25887   /* We already set the file and line above.  Reset them now in case
25888      they changed as a result of calling regenerate_decl_from_template.  */
25889   input_location = DECL_SOURCE_LOCATION (d);
25890 
25891   if (VAR_P (d))
25892     {
25893       tree init;
25894       bool const_init = false;
25895 
25896       /* Clear out DECL_RTL; whatever was there before may not be right
25897 	 since we've reset the type of the declaration.  */
25898       SET_DECL_RTL (d, NULL);
25899       DECL_IN_AGGR_P (d) = 0;
25900 
25901       /* The initializer is placed in DECL_INITIAL by
25902 	 regenerate_decl_from_template so we don't need to
25903 	 push/pop_access_scope again here.  Pull it out so that
25904 	 cp_finish_decl can process it.  */
25905       init = DECL_INITIAL (d);
25906       DECL_INITIAL (d) = NULL_TREE;
25907       DECL_INITIALIZED_P (d) = 0;
25908 
25909       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
25910 	 initializer.  That function will defer actual emission until
25911 	 we have a chance to determine linkage.  */
25912       DECL_EXTERNAL (d) = 0;
25913 
25914       /* Enter the scope of D so that access-checking works correctly.  */
25915       bool enter_context = DECL_CLASS_SCOPE_P (d);
25916       if (enter_context)
25917         push_nested_class (DECL_CONTEXT (d));
25918 
25919       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
25920       int flags = (TINFO_VAR_DECLARED_CONSTINIT (DECL_TEMPLATE_INFO (d))
25921 		   ? LOOKUP_CONSTINIT : 0);
25922       cp_finish_decl (d, init, const_init, NULL_TREE, flags);
25923 
25924       if (enter_context)
25925         pop_nested_class ();
25926 
25927       if (variable_template_p (gen_tmpl))
25928 	note_variable_template_instantiation (d);
25929     }
25930   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
25931     synthesize_method (d);
25932   else if (TREE_CODE (d) == FUNCTION_DECL)
25933     {
25934       /* Set up the list of local specializations.  */
25935       local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
25936       tree block = NULL_TREE;
25937 
25938       /* Set up context.  */
25939       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
25940 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
25941 	block = push_stmt_list ();
25942       else
25943 	start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
25944 
25945       /* Some typedefs referenced from within the template code need to be
25946 	 access checked at template instantiation time, i.e now. These
25947 	 types were added to the template at parsing time. Let's get those
25948 	 and perform the access checks then.  */
25949       perform_typedefs_access_check (DECL_TEMPLATE_RESULT (td),
25950 				     args);
25951 
25952       /* Create substitution entries for the parameters.  */
25953       register_parameter_specializations (code_pattern, d);
25954 
25955       /* Substitute into the body of the function.  */
25956       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
25957 	tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
25958 			tf_warning_or_error, tmpl);
25959       else
25960 	{
25961 	  tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
25962 		       tf_warning_or_error, tmpl,
25963 		       /*integral_constant_expression_p=*/false);
25964 
25965 	  /* Set the current input_location to the end of the function
25966 	     so that finish_function knows where we are.  */
25967 	  input_location
25968 	    = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
25969 
25970 	  /* Remember if we saw an infinite loop in the template.  */
25971 	  current_function_infinite_loop
25972 	    = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
25973 	}
25974 
25975       /* Finish the function.  */
25976       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
25977 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
25978 	DECL_SAVED_TREE (d) = pop_stmt_list (block);
25979       else
25980 	{
25981 	  d = finish_function (/*inline_p=*/false);
25982 	  expand_or_defer_fn (d);
25983 	}
25984 
25985       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
25986 	cp_check_omp_declare_reduction (d);
25987     }
25988 
25989   /* We're not deferring instantiation any more.  */
25990   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
25991 
25992   if (push_to_top)
25993     pop_from_top_level ();
25994   else
25995     pop_function_context ();
25996 
25997   if (nested)
25998     restore_omp_privatization_clauses (omp_privatization_save);
25999 
26000 out:
26001   pop_deferring_access_checks ();
26002   timevar_pop (TV_TEMPLATE_INST);
26003   pop_tinst_level ();
26004   input_location = saved_loc;
26005   cp_unevaluated_operand = saved_unevaluated_operand;
26006   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
26007 
26008   return d;
26009 }
26010 
26011 /* Run through the list of templates that we wish we could
26012    instantiate, and instantiate any we can.  RETRIES is the
26013    number of times we retry pending template instantiation.  */
26014 
26015 void
instantiate_pending_templates(int retries)26016 instantiate_pending_templates (int retries)
26017 {
26018   int reconsider;
26019   location_t saved_loc = input_location;
26020 
26021   /* Instantiating templates may trigger vtable generation.  This in turn
26022      may require further template instantiations.  We place a limit here
26023      to avoid infinite loop.  */
26024   if (pending_templates && retries >= max_tinst_depth)
26025     {
26026       tree decl = pending_templates->tinst->maybe_get_node ();
26027 
26028       fatal_error (input_location,
26029 		   "template instantiation depth exceeds maximum of %d"
26030 		   " instantiating %q+D, possibly from virtual table generation"
26031 		   " (use %<-ftemplate-depth=%> to increase the maximum)",
26032 		   max_tinst_depth, decl);
26033       if (TREE_CODE (decl) == FUNCTION_DECL)
26034 	/* Pretend that we defined it.  */
26035 	DECL_INITIAL (decl) = error_mark_node;
26036       return;
26037     }
26038 
26039   do
26040     {
26041       struct pending_template **t = &pending_templates;
26042       struct pending_template *last = NULL;
26043       reconsider = 0;
26044       while (*t)
26045 	{
26046 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
26047 	  bool complete = false;
26048 
26049 	  if (TYPE_P (instantiation))
26050 	    {
26051 	      if (!COMPLETE_TYPE_P (instantiation))
26052 		{
26053 		  instantiate_class_template (instantiation);
26054 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
26055 		    for (tree fld = TYPE_FIELDS (instantiation);
26056 			 fld; fld = TREE_CHAIN (fld))
26057 		      if ((VAR_P (fld)
26058 			   || (TREE_CODE (fld) == FUNCTION_DECL
26059 			       && !DECL_ARTIFICIAL (fld)))
26060 			  && DECL_TEMPLATE_INSTANTIATION (fld))
26061 			instantiate_decl (fld,
26062 					  /*defer_ok=*/false,
26063 					  /*expl_inst_class_mem_p=*/false);
26064 
26065 		  if (COMPLETE_TYPE_P (instantiation))
26066 		    reconsider = 1;
26067 		}
26068 
26069 	      complete = COMPLETE_TYPE_P (instantiation);
26070 	    }
26071 	  else
26072 	    {
26073 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
26074 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
26075 		{
26076 		  instantiation
26077 		    = instantiate_decl (instantiation,
26078 					/*defer_ok=*/false,
26079 					/*expl_inst_class_mem_p=*/false);
26080 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
26081 		    reconsider = 1;
26082 		}
26083 
26084 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
26085 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
26086 	    }
26087 
26088 	  if (complete)
26089 	    {
26090 	      /* If INSTANTIATION has been instantiated, then we don't
26091 		 need to consider it again in the future.  */
26092 	      struct pending_template *drop = *t;
26093 	      *t = (*t)->next;
26094 	      set_refcount_ptr (drop->tinst);
26095 	      pending_template_freelist ().free (drop);
26096 	    }
26097 	  else
26098 	    {
26099 	      last = *t;
26100 	      t = &(*t)->next;
26101 	    }
26102 	  tinst_depth = 0;
26103 	  set_refcount_ptr (current_tinst_level);
26104 	}
26105       last_pending_template = last;
26106     }
26107   while (reconsider);
26108 
26109   input_location = saved_loc;
26110 }
26111 
26112 /* Substitute ARGVEC into T, which is a list of initializers for
26113    either base class or a non-static data member.  The TREE_PURPOSEs
26114    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
26115    instantiate_decl.  */
26116 
26117 static tree
tsubst_initializer_list(tree t,tree argvec)26118 tsubst_initializer_list (tree t, tree argvec)
26119 {
26120   tree inits = NULL_TREE;
26121   tree target_ctor = error_mark_node;
26122 
26123   for (; t; t = TREE_CHAIN (t))
26124     {
26125       tree decl;
26126       tree init;
26127       tree expanded_bases = NULL_TREE;
26128       tree expanded_arguments = NULL_TREE;
26129       int i, len = 1;
26130 
26131       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
26132         {
26133           tree expr;
26134           tree arg;
26135 
26136           /* Expand the base class expansion type into separate base
26137              classes.  */
26138           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
26139                                                  tf_warning_or_error,
26140                                                  NULL_TREE);
26141           if (expanded_bases == error_mark_node)
26142             continue;
26143 
26144           /* We'll be building separate TREE_LISTs of arguments for
26145              each base.  */
26146           len = TREE_VEC_LENGTH (expanded_bases);
26147           expanded_arguments = make_tree_vec (len);
26148           for (i = 0; i < len; i++)
26149             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
26150 
26151           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
26152              expand each argument in the TREE_VALUE of t.  */
26153           expr = make_node (EXPR_PACK_EXPANSION);
26154 	  PACK_EXPANSION_LOCAL_P (expr) = true;
26155           PACK_EXPANSION_PARAMETER_PACKS (expr) =
26156             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
26157 
26158 	  if (TREE_VALUE (t) == void_type_node)
26159 	    /* VOID_TYPE_NODE is used to indicate
26160 	       value-initialization.  */
26161 	    {
26162 	      for (i = 0; i < len; i++)
26163 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
26164 	    }
26165 	  else
26166 	    {
26167 	      /* Substitute parameter packs into each argument in the
26168 		 TREE_LIST.  */
26169 	      in_base_initializer = 1;
26170 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
26171 		{
26172 		  tree expanded_exprs;
26173 
26174 		  /* Expand the argument.  */
26175 		  SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
26176 		  expanded_exprs
26177 		    = tsubst_pack_expansion (expr, argvec,
26178 					     tf_warning_or_error,
26179 					     NULL_TREE);
26180 		  if (expanded_exprs == error_mark_node)
26181 		    continue;
26182 
26183 		  /* Prepend each of the expanded expressions to the
26184 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
26185 		  for (i = 0; i < len; i++)
26186 		    {
26187 		      TREE_VEC_ELT (expanded_arguments, i) =
26188 			tree_cons (NULL_TREE,
26189 				   TREE_VEC_ELT (expanded_exprs, i),
26190 				   TREE_VEC_ELT (expanded_arguments, i));
26191 		    }
26192 		}
26193 	      in_base_initializer = 0;
26194 
26195 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
26196 		 since we built them backwards.  */
26197 	      for (i = 0; i < len; i++)
26198 		{
26199 		  TREE_VEC_ELT (expanded_arguments, i) =
26200 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
26201 		}
26202 	    }
26203         }
26204 
26205       for (i = 0; i < len; ++i)
26206         {
26207           if (expanded_bases)
26208             {
26209               decl = TREE_VEC_ELT (expanded_bases, i);
26210               decl = expand_member_init (decl);
26211               init = TREE_VEC_ELT (expanded_arguments, i);
26212             }
26213           else
26214             {
26215 	      tree tmp;
26216               decl = tsubst_copy (TREE_PURPOSE (t), argvec,
26217                                   tf_warning_or_error, NULL_TREE);
26218 
26219               decl = expand_member_init (decl);
26220               if (decl && !DECL_P (decl))
26221                 in_base_initializer = 1;
26222 
26223 	      init = TREE_VALUE (t);
26224 	      tmp = init;
26225 	      if (init != void_type_node)
26226 		init = tsubst_expr (init, argvec,
26227 				    tf_warning_or_error, NULL_TREE,
26228 				    /*integral_constant_expression_p=*/false);
26229 	      if (init == NULL_TREE && tmp != NULL_TREE)
26230 		/* If we had an initializer but it instantiated to nothing,
26231 		   value-initialize the object.  This will only occur when
26232 		   the initializer was a pack expansion where the parameter
26233 		   packs used in that expansion were of length zero.  */
26234 		init = void_type_node;
26235               in_base_initializer = 0;
26236             }
26237 
26238 	  if (target_ctor != error_mark_node
26239 	      && init != error_mark_node)
26240 	    {
26241 	      error ("mem-initializer for %qD follows constructor delegation",
26242 		     decl);
26243 	      return inits;
26244 	    }
26245 	  /* Look for a target constructor. */
26246 	  if (init != error_mark_node
26247 	      && decl && CLASS_TYPE_P (decl)
26248 	      && same_type_p (decl, current_class_type))
26249 	    {
26250 	      maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
26251 	      if (inits)
26252 		{
26253 		  error ("constructor delegation follows mem-initializer for %qD",
26254 			 TREE_PURPOSE (inits));
26255 		  continue;
26256 		}
26257 	      target_ctor = init;
26258 	    }
26259 
26260           if (decl)
26261             {
26262               init = build_tree_list (decl, init);
26263               TREE_CHAIN (init) = inits;
26264               inits = init;
26265             }
26266         }
26267     }
26268   return inits;
26269 }
26270 
26271 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
26272 
26273 static void
set_current_access_from_decl(tree decl)26274 set_current_access_from_decl (tree decl)
26275 {
26276   if (TREE_PRIVATE (decl))
26277     current_access_specifier = access_private_node;
26278   else if (TREE_PROTECTED (decl))
26279     current_access_specifier = access_protected_node;
26280   else
26281     current_access_specifier = access_public_node;
26282 }
26283 
26284 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
26285    is the instantiation (which should have been created with
26286    start_enum) and ARGS are the template arguments to use.  */
26287 
26288 static void
tsubst_enum(tree tag,tree newtag,tree args)26289 tsubst_enum (tree tag, tree newtag, tree args)
26290 {
26291   tree e;
26292 
26293   if (SCOPED_ENUM_P (newtag))
26294     begin_scope (sk_scoped_enum, newtag);
26295 
26296   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
26297     {
26298       tree value;
26299       tree decl;
26300 
26301       decl = TREE_VALUE (e);
26302       /* Note that in a template enum, the TREE_VALUE is the
26303 	 CONST_DECL, not the corresponding INTEGER_CST.  */
26304       value = tsubst_expr (DECL_INITIAL (decl),
26305 			   args, tf_warning_or_error, NULL_TREE,
26306 			   /*integral_constant_expression_p=*/true);
26307 
26308       /* Give this enumeration constant the correct access.  */
26309       set_current_access_from_decl (decl);
26310 
26311       /* Actually build the enumerator itself.  Here we're assuming that
26312 	 enumerators can't have dependent attributes.  */
26313       build_enumerator (DECL_NAME (decl), value, newtag,
26314 			DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
26315     }
26316 
26317   if (SCOPED_ENUM_P (newtag))
26318     finish_scope ();
26319 
26320   finish_enum_value_list (newtag);
26321   finish_enum (newtag);
26322 
26323   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
26324     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
26325 }
26326 
26327 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
26328    its type -- but without substituting the innermost set of template
26329    arguments.  So, innermost set of template parameters will appear in
26330    the type.  */
26331 
26332 tree
get_mostly_instantiated_function_type(tree decl)26333 get_mostly_instantiated_function_type (tree decl)
26334 {
26335   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
26336   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
26337 }
26338 
26339 /* Return truthvalue if we're processing a template different from
26340    the last one involved in diagnostics.  */
26341 bool
problematic_instantiation_changed(void)26342 problematic_instantiation_changed (void)
26343 {
26344   return current_tinst_level != last_error_tinst_level;
26345 }
26346 
26347 /* Remember current template involved in diagnostics.  */
26348 void
record_last_problematic_instantiation(void)26349 record_last_problematic_instantiation (void)
26350 {
26351   set_refcount_ptr (last_error_tinst_level, current_tinst_level);
26352 }
26353 
26354 struct tinst_level *
current_instantiation(void)26355 current_instantiation (void)
26356 {
26357   return current_tinst_level;
26358 }
26359 
26360 /* Return TRUE if current_function_decl is being instantiated, false
26361    otherwise.  */
26362 
26363 bool
instantiating_current_function_p(void)26364 instantiating_current_function_p (void)
26365 {
26366   return (current_instantiation ()
26367 	  && (current_instantiation ()->maybe_get_node ()
26368 	      == current_function_decl));
26369 }
26370 
26371 /* [temp.param] Check that template non-type parm TYPE is of an allowable
26372    type.  Return false for ok, true for disallowed.  Issue error and
26373    inform messages under control of COMPLAIN.  */
26374 
26375 static bool
invalid_nontype_parm_type_p(tree type,tsubst_flags_t complain)26376 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
26377 {
26378   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
26379     return false;
26380   else if (TYPE_PTR_P (type))
26381     return false;
26382   else if (TYPE_REF_P (type)
26383 	   && !TYPE_REF_IS_RVALUE (type))
26384     return false;
26385   else if (TYPE_PTRMEM_P (type))
26386     return false;
26387   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
26388     {
26389       if (CLASS_PLACEHOLDER_TEMPLATE (type) && cxx_dialect < cxx2a)
26390 	{
26391 	  if (complain & tf_error)
26392 	    error ("non-type template parameters of deduced class type only "
26393 		   "available with %<-std=c++2a%> or %<-std=gnu++2a%>");
26394 	  return true;
26395 	}
26396       return false;
26397     }
26398   else if (TREE_CODE (type) == TYPENAME_TYPE)
26399     return false;
26400   else if (TREE_CODE (type) == DECLTYPE_TYPE)
26401     return false;
26402   else if (TREE_CODE (type) == NULLPTR_TYPE)
26403     return false;
26404   /* A bound template template parm could later be instantiated to have a valid
26405      nontype parm type via an alias template.  */
26406   else if (cxx_dialect >= cxx11
26407 	   && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
26408     return false;
26409   else if (CLASS_TYPE_P (type))
26410     {
26411       if (cxx_dialect < cxx2a)
26412 	{
26413 	  if (complain & tf_error)
26414 	    error ("non-type template parameters of class type only available "
26415 		   "with %<-std=c++2a%> or %<-std=gnu++2a%>");
26416 	  return true;
26417 	}
26418       if (dependent_type_p (type))
26419 	return false;
26420       if (!complete_type_or_else (type, NULL_TREE))
26421 	return true;
26422       if (!structural_type_p (type))
26423 	{
26424 	  if (complain & tf_error)
26425 	    {
26426 	      auto_diagnostic_group d;
26427 	      error ("%qT is not a valid type for a template non-type "
26428 		     "parameter because it is not structural", type);
26429 	      structural_type_p (type, true);
26430 	    }
26431 	  return true;
26432 	}
26433       return false;
26434     }
26435 
26436   if (complain & tf_error)
26437     {
26438       if (type == error_mark_node)
26439 	inform (input_location, "invalid template non-type parameter");
26440       else
26441 	error ("%q#T is not a valid type for a template non-type parameter",
26442 	       type);
26443     }
26444   return true;
26445 }
26446 
26447 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
26448    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
26449 
26450 static bool
dependent_type_p_r(tree type)26451 dependent_type_p_r (tree type)
26452 {
26453   tree scope;
26454 
26455   /* [temp.dep.type]
26456 
26457      A type is dependent if it is:
26458 
26459      -- a template parameter. Template template parameters are types
26460 	for us (since TYPE_P holds true for them) so we handle
26461 	them here.  */
26462   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
26463       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
26464     return true;
26465   /* -- a qualified-id with a nested-name-specifier which contains a
26466 	class-name that names a dependent type or whose unqualified-id
26467 	names a dependent type.  */
26468   if (TREE_CODE (type) == TYPENAME_TYPE)
26469     return true;
26470 
26471   /* An alias template specialization can be dependent even if the
26472      resulting type is not.  */
26473   if (dependent_alias_template_spec_p (type, nt_transparent))
26474     return true;
26475 
26476   /* -- a cv-qualified type where the cv-unqualified type is
26477 	dependent.
26478      No code is necessary for this bullet; the code below handles
26479      cv-qualified types, and we don't want to strip aliases with
26480      TYPE_MAIN_VARIANT because of DR 1558.  */
26481   /* -- a compound type constructed from any dependent type.  */
26482   if (TYPE_PTRMEM_P (type))
26483     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
26484 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
26485 					   (type)));
26486   else if (INDIRECT_TYPE_P (type))
26487     return dependent_type_p (TREE_TYPE (type));
26488   else if (FUNC_OR_METHOD_TYPE_P (type))
26489     {
26490       tree arg_type;
26491 
26492       if (dependent_type_p (TREE_TYPE (type)))
26493 	return true;
26494       for (arg_type = TYPE_ARG_TYPES (type);
26495 	   arg_type;
26496 	   arg_type = TREE_CHAIN (arg_type))
26497 	if (dependent_type_p (TREE_VALUE (arg_type)))
26498 	  return true;
26499       if (cxx_dialect >= cxx17)
26500 	/* A value-dependent noexcept-specifier makes the type dependent.  */
26501 	if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
26502 	  if (tree noex = TREE_PURPOSE (spec))
26503 	    /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
26504 	       affect overload resolution and treating it as dependent breaks
26505 	       things.  Same for an unparsed noexcept expression.  */
26506 	    if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
26507 		&& TREE_CODE (noex) != DEFERRED_PARSE
26508 		&& value_dependent_expression_p (noex))
26509 	      return true;
26510       return false;
26511     }
26512   /* -- an array type constructed from any dependent type or whose
26513 	size is specified by a constant expression that is
26514 	value-dependent.
26515 
26516         We checked for type- and value-dependence of the bounds in
26517         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
26518   if (TREE_CODE (type) == ARRAY_TYPE)
26519     {
26520       if (TYPE_DOMAIN (type)
26521 	  && dependent_type_p (TYPE_DOMAIN (type)))
26522 	return true;
26523       return dependent_type_p (TREE_TYPE (type));
26524     }
26525 
26526   /* -- a template-id in which either the template name is a template
26527      parameter ...  */
26528   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
26529     return true;
26530   /* ... or any of the template arguments is a dependent type or
26531 	an expression that is type-dependent or value-dependent.  */
26532   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
26533 	   && (any_dependent_template_arguments_p
26534 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
26535     return true;
26536 
26537   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
26538      dependent; if the argument of the `typeof' expression is not
26539      type-dependent, then it should already been have resolved.  */
26540   if (TREE_CODE (type) == TYPEOF_TYPE
26541       || TREE_CODE (type) == DECLTYPE_TYPE
26542       || TREE_CODE (type) == UNDERLYING_TYPE)
26543     return true;
26544 
26545   /* A template argument pack is dependent if any of its packed
26546      arguments are.  */
26547   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
26548     {
26549       tree args = ARGUMENT_PACK_ARGS (type);
26550       int i, len = TREE_VEC_LENGTH (args);
26551       for (i = 0; i < len; ++i)
26552         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
26553           return true;
26554     }
26555 
26556   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
26557      be template parameters.  */
26558   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
26559     return true;
26560 
26561   if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
26562     return true;
26563 
26564   /* The standard does not specifically mention types that are local
26565      to template functions or local classes, but they should be
26566      considered dependent too.  For example:
26567 
26568        template <int I> void f() {
26569 	 enum E { a = I };
26570 	 S<sizeof (E)> s;
26571        }
26572 
26573      The size of `E' cannot be known until the value of `I' has been
26574      determined.  Therefore, `E' must be considered dependent.  */
26575   scope = TYPE_CONTEXT (type);
26576   if (scope && TYPE_P (scope))
26577     return dependent_type_p (scope);
26578   /* Don't use type_dependent_expression_p here, as it can lead
26579      to infinite recursion trying to determine whether a lambda
26580      nested in a lambda is dependent (c++/47687).  */
26581   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
26582 	   && DECL_LANG_SPECIFIC (scope)
26583 	   && DECL_TEMPLATE_INFO (scope)
26584 	   && (any_dependent_template_arguments_p
26585 	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
26586     return true;
26587 
26588   /* Other types are non-dependent.  */
26589   return false;
26590 }
26591 
26592 /* Returns TRUE if TYPE is dependent, in the sense of
26593    [temp.dep.type].  Note that a NULL type is considered dependent.  */
26594 
26595 bool
dependent_type_p(tree type)26596 dependent_type_p (tree type)
26597 {
26598   /* If there are no template parameters in scope, then there can't be
26599      any dependent types.  */
26600   if (!processing_template_decl)
26601     {
26602       /* If we are not processing a template, then nobody should be
26603 	 providing us with a dependent type.  */
26604       gcc_assert (type);
26605       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
26606       return false;
26607     }
26608 
26609   /* If the type is NULL, we have not computed a type for the entity
26610      in question; in that case, the type is dependent.  */
26611   if (!type)
26612     return true;
26613 
26614   /* Erroneous types can be considered non-dependent.  */
26615   if (type == error_mark_node)
26616     return false;
26617 
26618   /* Getting here with global_type_node means we improperly called this
26619      function on the TREE_TYPE of an IDENTIFIER_NODE.  */
26620   gcc_checking_assert (type != global_type_node);
26621 
26622   /* If we have not already computed the appropriate value for TYPE,
26623      do so now.  */
26624   if (!TYPE_DEPENDENT_P_VALID (type))
26625     {
26626       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
26627       TYPE_DEPENDENT_P_VALID (type) = 1;
26628     }
26629 
26630   return TYPE_DEPENDENT_P (type);
26631 }
26632 
26633 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
26634    lookup.  In other words, a dependent type that is not the current
26635    instantiation.  */
26636 
26637 bool
dependent_scope_p(tree scope)26638 dependent_scope_p (tree scope)
26639 {
26640   return (scope && TYPE_P (scope) && dependent_type_p (scope)
26641 	  && !currently_open_class (scope));
26642 }
26643 
26644 /* T is a SCOPE_REF.  Return whether it represents a non-static member of
26645    an unknown base of 'this' (and is therefore instantiation-dependent).  */
26646 
26647 static bool
unknown_base_ref_p(tree t)26648 unknown_base_ref_p (tree t)
26649 {
26650   if (!current_class_ptr)
26651     return false;
26652 
26653   tree mem = TREE_OPERAND (t, 1);
26654   if (shared_member_p (mem))
26655     return false;
26656 
26657   tree cur = current_nonlambda_class_type ();
26658   if (!any_dependent_bases_p (cur))
26659     return false;
26660 
26661   tree ctx = TREE_OPERAND (t, 0);
26662   if (DERIVED_FROM_P (ctx, cur))
26663     return false;
26664 
26665   return true;
26666 }
26667 
26668 /* T is a SCOPE_REF; return whether we need to consider it
26669     instantiation-dependent so that we can check access at instantiation
26670     time even though we know which member it resolves to.  */
26671 
26672 static bool
instantiation_dependent_scope_ref_p(tree t)26673 instantiation_dependent_scope_ref_p (tree t)
26674 {
26675   if (DECL_P (TREE_OPERAND (t, 1))
26676       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
26677       && !unknown_base_ref_p (t)
26678       && accessible_in_template_p (TREE_OPERAND (t, 0),
26679 				   TREE_OPERAND (t, 1)))
26680     return false;
26681   else
26682     return true;
26683 }
26684 
26685 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
26686    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
26687    expression.  */
26688 
26689 /* Note that this predicate is not appropriate for general expressions;
26690    only constant expressions (that satisfy potential_constant_expression)
26691    can be tested for value dependence.  */
26692 
26693 bool
value_dependent_expression_p(tree expression)26694 value_dependent_expression_p (tree expression)
26695 {
26696   if (!processing_template_decl || expression == NULL_TREE)
26697     return false;
26698 
26699   /* A type-dependent expression is also value-dependent.  */
26700   if (type_dependent_expression_p (expression))
26701     return true;
26702 
26703   switch (TREE_CODE (expression))
26704     {
26705     case BASELINK:
26706       /* A dependent member function of the current instantiation.  */
26707       return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
26708 
26709     case FUNCTION_DECL:
26710       /* A dependent member function of the current instantiation.  */
26711       if (DECL_CLASS_SCOPE_P (expression)
26712 	  && dependent_type_p (DECL_CONTEXT (expression)))
26713 	return true;
26714       break;
26715 
26716     case IDENTIFIER_NODE:
26717       /* A name that has not been looked up -- must be dependent.  */
26718       return true;
26719 
26720     case TEMPLATE_PARM_INDEX:
26721       /* A non-type template parm.  */
26722       return true;
26723 
26724     case CONST_DECL:
26725       /* A non-type template parm.  */
26726       if (DECL_TEMPLATE_PARM_P (expression))
26727 	return true;
26728       return value_dependent_expression_p (DECL_INITIAL (expression));
26729 
26730     case VAR_DECL:
26731        /* A constant with literal type and is initialized
26732 	  with an expression that is value-dependent.  */
26733       if (DECL_DEPENDENT_INIT_P (expression)
26734 	  /* FIXME cp_finish_decl doesn't fold reference initializers.  */
26735 	  || TYPE_REF_P (TREE_TYPE (expression)))
26736 	return true;
26737       if (DECL_HAS_VALUE_EXPR_P (expression))
26738 	{
26739 	  tree value_expr = DECL_VALUE_EXPR (expression);
26740 	  if (value_dependent_expression_p (value_expr)
26741 	      /* __PRETTY_FUNCTION__ inside a template function is dependent
26742 		 on the name of the function.  */
26743 	      || (DECL_PRETTY_FUNCTION_P (expression)
26744 		  /* It might be used in a template, but not a template
26745 		     function, in which case its DECL_VALUE_EXPR will be
26746 		     "top level".  */
26747 		  && value_expr == error_mark_node))
26748 	    return true;
26749 	}
26750       return false;
26751 
26752     case DYNAMIC_CAST_EXPR:
26753     case STATIC_CAST_EXPR:
26754     case CONST_CAST_EXPR:
26755     case REINTERPRET_CAST_EXPR:
26756     case CAST_EXPR:
26757     case IMPLICIT_CONV_EXPR:
26758       /* These expressions are value-dependent if the type to which
26759 	 the cast occurs is dependent or the expression being casted
26760 	 is value-dependent.  */
26761       {
26762 	tree type = TREE_TYPE (expression);
26763 
26764 	if (dependent_type_p (type))
26765 	  return true;
26766 
26767 	/* A functional cast has a list of operands.  */
26768 	expression = TREE_OPERAND (expression, 0);
26769 	if (!expression)
26770 	  {
26771 	    /* If there are no operands, it must be an expression such
26772 	       as "int()". This should not happen for aggregate types
26773 	       because it would form non-constant expressions.  */
26774 	    gcc_assert (cxx_dialect >= cxx11
26775 			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
26776 
26777 	    return false;
26778 	  }
26779 
26780 	if (TREE_CODE (expression) == TREE_LIST)
26781 	  return any_value_dependent_elements_p (expression);
26782 
26783 	return value_dependent_expression_p (expression);
26784       }
26785 
26786     case SIZEOF_EXPR:
26787       if (SIZEOF_EXPR_TYPE_P (expression))
26788 	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
26789       /* FALLTHRU */
26790     case ALIGNOF_EXPR:
26791     case TYPEID_EXPR:
26792       /* A `sizeof' expression is value-dependent if the operand is
26793 	 type-dependent or is a pack expansion.  */
26794       expression = TREE_OPERAND (expression, 0);
26795       if (PACK_EXPANSION_P (expression))
26796         return true;
26797       else if (TYPE_P (expression))
26798 	return dependent_type_p (expression);
26799       return instantiation_dependent_uneval_expression_p (expression);
26800 
26801     case AT_ENCODE_EXPR:
26802       /* An 'encode' expression is value-dependent if the operand is
26803 	 type-dependent.  */
26804       expression = TREE_OPERAND (expression, 0);
26805       return dependent_type_p (expression);
26806 
26807     case NOEXCEPT_EXPR:
26808       expression = TREE_OPERAND (expression, 0);
26809       return instantiation_dependent_uneval_expression_p (expression);
26810 
26811     case SCOPE_REF:
26812       /* All instantiation-dependent expressions should also be considered
26813 	 value-dependent.  */
26814       return instantiation_dependent_scope_ref_p (expression);
26815 
26816     case COMPONENT_REF:
26817       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
26818 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
26819 
26820     case NONTYPE_ARGUMENT_PACK:
26821       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
26822          is value-dependent.  */
26823       {
26824         tree values = ARGUMENT_PACK_ARGS (expression);
26825         int i, len = TREE_VEC_LENGTH (values);
26826 
26827         for (i = 0; i < len; ++i)
26828           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
26829             return true;
26830 
26831         return false;
26832       }
26833 
26834     case TRAIT_EXPR:
26835       {
26836 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
26837 
26838 	if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
26839 	  return true;
26840 
26841 	if (!type2)
26842 	  return false;
26843 
26844 	if (TREE_CODE (type2) != TREE_LIST)
26845 	  return dependent_type_p (type2);
26846 
26847 	for (; type2; type2 = TREE_CHAIN (type2))
26848 	  if (dependent_type_p (TREE_VALUE (type2)))
26849 	    return true;
26850 
26851 	return false;
26852       }
26853 
26854     case MODOP_EXPR:
26855       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
26856 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
26857 
26858     case ARRAY_REF:
26859       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
26860 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
26861 
26862     case ADDR_EXPR:
26863       {
26864 	tree op = TREE_OPERAND (expression, 0);
26865 	return (value_dependent_expression_p (op)
26866 		|| has_value_dependent_address (op));
26867       }
26868 
26869     case REQUIRES_EXPR:
26870       /* Treat all requires-expressions as value-dependent so
26871          we don't try to fold them.  */
26872       return true;
26873 
26874     case TYPE_REQ:
26875       return dependent_type_p (TREE_OPERAND (expression, 0));
26876 
26877     case CALL_EXPR:
26878       {
26879 	if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
26880 	  return true;
26881 	tree fn = get_callee_fndecl (expression);
26882 	int i, nargs;
26883 	nargs = call_expr_nargs (expression);
26884 	for (i = 0; i < nargs; ++i)
26885 	  {
26886 	    tree op = CALL_EXPR_ARG (expression, i);
26887 	    /* In a call to a constexpr member function, look through the
26888 	       implicit ADDR_EXPR on the object argument so that it doesn't
26889 	       cause the call to be considered value-dependent.  We also
26890 	       look through it in potential_constant_expression.  */
26891 	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
26892 		&& DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
26893 		&& TREE_CODE (op) == ADDR_EXPR)
26894 	      op = TREE_OPERAND (op, 0);
26895 	    if (value_dependent_expression_p (op))
26896 	      return true;
26897 	  }
26898 	return false;
26899       }
26900 
26901     case TEMPLATE_ID_EXPR:
26902       return concept_definition_p (TREE_OPERAND (expression, 0));
26903 
26904     case CONSTRUCTOR:
26905       {
26906 	unsigned ix;
26907 	tree val;
26908 	if (dependent_type_p (TREE_TYPE (expression)))
26909 	  return true;
26910 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
26911 	  if (value_dependent_expression_p (val))
26912 	    return true;
26913 	return false;
26914       }
26915 
26916     case STMT_EXPR:
26917       /* Treat a GNU statement expression as dependent to avoid crashing
26918 	 under instantiate_non_dependent_expr; it can't be constant.  */
26919       return true;
26920 
26921     default:
26922       /* A constant expression is value-dependent if any subexpression is
26923 	 value-dependent.  */
26924       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
26925 	{
26926 	case tcc_reference:
26927 	case tcc_unary:
26928 	case tcc_comparison:
26929 	case tcc_binary:
26930 	case tcc_expression:
26931 	case tcc_vl_exp:
26932 	  {
26933 	    int i, len = cp_tree_operand_length (expression);
26934 
26935 	    for (i = 0; i < len; i++)
26936 	      {
26937 		tree t = TREE_OPERAND (expression, i);
26938 
26939 		/* In some cases, some of the operands may be missing.
26940 		   (For example, in the case of PREDECREMENT_EXPR, the
26941 		   amount to increment by may be missing.)  That doesn't
26942 		   make the expression dependent.  */
26943 		if (t && value_dependent_expression_p (t))
26944 		  return true;
26945 	      }
26946 	  }
26947 	  break;
26948 	default:
26949 	  break;
26950 	}
26951       break;
26952     }
26953 
26954   /* The expression is not value-dependent.  */
26955   return false;
26956 }
26957 
26958 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
26959    [temp.dep.expr].  Note that an expression with no type is
26960    considered dependent.  Other parts of the compiler arrange for an
26961    expression with type-dependent subexpressions to have no type, so
26962    this function doesn't have to be fully recursive.  */
26963 
26964 bool
type_dependent_expression_p(tree expression)26965 type_dependent_expression_p (tree expression)
26966 {
26967   if (!processing_template_decl)
26968     return false;
26969 
26970   if (expression == NULL_TREE || expression == error_mark_node)
26971     return false;
26972 
26973   STRIP_ANY_LOCATION_WRAPPER (expression);
26974 
26975   /* An unresolved name is always dependent.  */
26976   if (identifier_p (expression)
26977       || TREE_CODE (expression) == USING_DECL
26978       || TREE_CODE (expression) == WILDCARD_DECL)
26979     return true;
26980 
26981   /* A lambda-expression in template context is dependent.  dependent_type_p is
26982      true for a lambda in the scope of a class or function template, but that
26983      doesn't cover all template contexts, like a default template argument.  */
26984   if (TREE_CODE (expression) == LAMBDA_EXPR)
26985     return true;
26986 
26987   /* A fold expression is type-dependent. */
26988   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
26989       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
26990       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
26991       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
26992     return true;
26993 
26994   /* Some expression forms are never type-dependent.  */
26995   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
26996       || TREE_CODE (expression) == SIZEOF_EXPR
26997       || TREE_CODE (expression) == ALIGNOF_EXPR
26998       || TREE_CODE (expression) == AT_ENCODE_EXPR
26999       || TREE_CODE (expression) == NOEXCEPT_EXPR
27000       || TREE_CODE (expression) == TRAIT_EXPR
27001       || TREE_CODE (expression) == TYPEID_EXPR
27002       || TREE_CODE (expression) == DELETE_EXPR
27003       || TREE_CODE (expression) == VEC_DELETE_EXPR
27004       || TREE_CODE (expression) == THROW_EXPR
27005       || TREE_CODE (expression) == REQUIRES_EXPR)
27006     return false;
27007 
27008   /* The types of these expressions depends only on the type to which
27009      the cast occurs.  */
27010   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
27011       || TREE_CODE (expression) == STATIC_CAST_EXPR
27012       || TREE_CODE (expression) == CONST_CAST_EXPR
27013       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
27014       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
27015       || TREE_CODE (expression) == CAST_EXPR)
27016     return dependent_type_p (TREE_TYPE (expression));
27017 
27018   /* The types of these expressions depends only on the type created
27019      by the expression.  */
27020   if (TREE_CODE (expression) == NEW_EXPR
27021       || TREE_CODE (expression) == VEC_NEW_EXPR)
27022     {
27023       /* For NEW_EXPR tree nodes created inside a template, either
27024 	 the object type itself or a TREE_LIST may appear as the
27025 	 operand 1.  */
27026       tree type = TREE_OPERAND (expression, 1);
27027       if (TREE_CODE (type) == TREE_LIST)
27028 	/* This is an array type.  We need to check array dimensions
27029 	   as well.  */
27030 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
27031 	       || value_dependent_expression_p
27032 		    (TREE_OPERAND (TREE_VALUE (type), 1));
27033       else
27034 	return dependent_type_p (type);
27035     }
27036 
27037   if (TREE_CODE (expression) == SCOPE_REF)
27038     {
27039       tree scope = TREE_OPERAND (expression, 0);
27040       tree name = TREE_OPERAND (expression, 1);
27041 
27042       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
27043 	 contains an identifier associated by name lookup with one or more
27044 	 declarations declared with a dependent type, or...a
27045 	 nested-name-specifier or qualified-id that names a member of an
27046 	 unknown specialization.  */
27047       return (type_dependent_expression_p (name)
27048 	      || dependent_scope_p (scope));
27049     }
27050 
27051   if (TREE_CODE (expression) == TEMPLATE_DECL
27052       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
27053     return uses_outer_template_parms (expression);
27054 
27055   if (TREE_CODE (expression) == STMT_EXPR)
27056     expression = stmt_expr_value_expr (expression);
27057 
27058   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
27059     {
27060       tree elt;
27061       unsigned i;
27062 
27063       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
27064 	{
27065 	  if (type_dependent_expression_p (elt))
27066 	    return true;
27067 	}
27068       return false;
27069     }
27070 
27071   /* A static data member of the current instantiation with incomplete
27072      array type is type-dependent, as the definition and specializations
27073      can have different bounds.  */
27074   if (VAR_P (expression)
27075       && DECL_CLASS_SCOPE_P (expression)
27076       && dependent_type_p (DECL_CONTEXT (expression))
27077       && VAR_HAD_UNKNOWN_BOUND (expression))
27078     return true;
27079 
27080   /* An array of unknown bound depending on a variadic parameter, eg:
27081 
27082      template<typename... Args>
27083        void foo (Args... args)
27084        {
27085          int arr[] = { args... };
27086        }
27087 
27088      template<int... vals>
27089        void bar ()
27090        {
27091          int arr[] = { vals... };
27092        }
27093 
27094      If the array has no length and has an initializer, it must be that
27095      we couldn't determine its length in cp_complete_array_type because
27096      it is dependent.  */
27097   if (VAR_P (expression)
27098       && TREE_TYPE (expression) != NULL_TREE
27099       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
27100       && !TYPE_DOMAIN (TREE_TYPE (expression))
27101       && DECL_INITIAL (expression))
27102    return true;
27103 
27104   /* A function or variable template-id is type-dependent if it has any
27105      dependent template arguments.  */
27106   if (VAR_OR_FUNCTION_DECL_P (expression)
27107       && DECL_LANG_SPECIFIC (expression)
27108       && DECL_TEMPLATE_INFO (expression))
27109     {
27110       /* Consider the innermost template arguments, since those are the ones
27111 	 that come from the template-id; the template arguments for the
27112 	 enclosing class do not make it type-dependent unless they are used in
27113 	 the type of the decl.  */
27114       if (instantiates_primary_template_p (expression)
27115 	  && (any_dependent_template_arguments_p
27116 	      (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
27117 	return true;
27118     }
27119 
27120   /* Otherwise, if the function decl isn't from a dependent scope, it can't be
27121      type-dependent.  Checking this is important for functions with auto return
27122      type, which looks like a dependent type.  */
27123   if (TREE_CODE (expression) == FUNCTION_DECL
27124       && !(DECL_CLASS_SCOPE_P (expression)
27125 	   && dependent_type_p (DECL_CONTEXT (expression)))
27126       && !(DECL_LANG_SPECIFIC (expression)
27127 	   && DECL_FRIEND_P (expression)
27128 	   && (!DECL_FRIEND_CONTEXT (expression)
27129 	       || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
27130       && !DECL_LOCAL_FUNCTION_P (expression))
27131     {
27132       gcc_assert (!dependent_type_p (TREE_TYPE (expression))
27133 		  || undeduced_auto_decl (expression));
27134       return false;
27135     }
27136 
27137   /* Always dependent, on the number of arguments if nothing else.  */
27138   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
27139     return true;
27140 
27141   if (TREE_TYPE (expression) == unknown_type_node)
27142     {
27143       if (TREE_CODE (expression) == ADDR_EXPR)
27144 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
27145       if (TREE_CODE (expression) == COMPONENT_REF
27146 	  || TREE_CODE (expression) == OFFSET_REF)
27147 	{
27148 	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
27149 	    return true;
27150 	  expression = TREE_OPERAND (expression, 1);
27151 	  if (identifier_p (expression))
27152 	    return false;
27153 	}
27154       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
27155       if (TREE_CODE (expression) == SCOPE_REF)
27156 	return false;
27157 
27158       /* CO_AWAIT/YIELD_EXPR with unknown type is always dependent.  */
27159       if (TREE_CODE (expression) == CO_AWAIT_EXPR
27160 	  || TREE_CODE (expression) == CO_YIELD_EXPR)
27161 	return true;
27162 
27163       if (BASELINK_P (expression))
27164 	{
27165 	  if (BASELINK_OPTYPE (expression)
27166 	      && dependent_type_p (BASELINK_OPTYPE (expression)))
27167 	    return true;
27168 	  expression = BASELINK_FUNCTIONS (expression);
27169 	}
27170 
27171       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
27172 	{
27173 	  if (any_dependent_template_arguments_p
27174 	      (TREE_OPERAND (expression, 1)))
27175 	    return true;
27176 	  expression = TREE_OPERAND (expression, 0);
27177 	  if (identifier_p (expression))
27178 	    return true;
27179 	}
27180 
27181       gcc_assert (OVL_P (expression));
27182 
27183       for (lkp_iterator iter (expression); iter; ++iter)
27184 	if (type_dependent_expression_p (*iter))
27185 	  return true;
27186 
27187       return false;
27188     }
27189 
27190   /* The type of a non-type template parm declared with a placeholder type
27191      depends on the corresponding template argument, even though
27192      placeholders are not normally considered dependent.  */
27193   if (TREE_CODE (expression) == TEMPLATE_PARM_INDEX
27194       && is_auto (TREE_TYPE (expression)))
27195     return true;
27196 
27197   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
27198 
27199   /* Dependent type attributes might not have made it from the decl to
27200      the type yet.  */
27201   if (DECL_P (expression)
27202       && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
27203     return true;
27204 
27205   return (dependent_type_p (TREE_TYPE (expression)));
27206 }
27207 
27208 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
27209    type-dependent if the expression refers to a member of the current
27210    instantiation and the type of the referenced member is dependent, or the
27211    class member access expression refers to a member of an unknown
27212    specialization.
27213 
27214    This function returns true if the OBJECT in such a class member access
27215    expression is of an unknown specialization.  */
27216 
27217 bool
type_dependent_object_expression_p(tree object)27218 type_dependent_object_expression_p (tree object)
27219 {
27220   /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
27221      dependent.  */
27222   if (TREE_CODE (object) == IDENTIFIER_NODE)
27223     return true;
27224   tree scope = TREE_TYPE (object);
27225   return (!scope || dependent_scope_p (scope));
27226 }
27227 
27228 /* walk_tree callback function for instantiation_dependent_expression_p,
27229    below.  Returns non-zero if a dependent subexpression is found.  */
27230 
27231 static tree
instantiation_dependent_r(tree * tp,int * walk_subtrees,void *)27232 instantiation_dependent_r (tree *tp, int *walk_subtrees,
27233 			   void * /*data*/)
27234 {
27235   if (TYPE_P (*tp))
27236     {
27237       /* We don't have to worry about decltype currently because decltype
27238 	 of an instantiation-dependent expr is a dependent type.  This
27239 	 might change depending on the resolution of DR 1172.  */
27240       *walk_subtrees = false;
27241       return NULL_TREE;
27242     }
27243   enum tree_code code = TREE_CODE (*tp);
27244   switch (code)
27245     {
27246       /* Don't treat an argument list as dependent just because it has no
27247 	 TREE_TYPE.  */
27248     case TREE_LIST:
27249     case TREE_VEC:
27250     case NONTYPE_ARGUMENT_PACK:
27251       return NULL_TREE;
27252 
27253     case TEMPLATE_PARM_INDEX:
27254       if (dependent_type_p (TREE_TYPE (*tp)))
27255 	return *tp;
27256       if (TEMPLATE_PARM_PARAMETER_PACK (*tp))
27257 	return *tp;
27258       /* We'll check value-dependence separately.  */
27259       return NULL_TREE;
27260 
27261       /* Handle expressions with type operands.  */
27262     case SIZEOF_EXPR:
27263     case ALIGNOF_EXPR:
27264     case TYPEID_EXPR:
27265     case AT_ENCODE_EXPR:
27266       {
27267 	tree op = TREE_OPERAND (*tp, 0);
27268 	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
27269 	  op = TREE_TYPE (op);
27270 	if (TYPE_P (op))
27271 	  {
27272 	    if (dependent_type_p (op))
27273 	      return *tp;
27274 	    else
27275 	      {
27276 		*walk_subtrees = false;
27277 		return NULL_TREE;
27278 	      }
27279 	  }
27280 	break;
27281       }
27282 
27283     case COMPONENT_REF:
27284       if (identifier_p (TREE_OPERAND (*tp, 1)))
27285 	/* In a template, finish_class_member_access_expr creates a
27286 	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
27287 	   type-dependent, so that we can check access control at
27288 	   instantiation time (PR 42277).  See also Core issue 1273.  */
27289 	return *tp;
27290       break;
27291 
27292     case SCOPE_REF:
27293       if (instantiation_dependent_scope_ref_p (*tp))
27294 	return *tp;
27295       else
27296 	break;
27297 
27298       /* Treat statement-expressions as dependent.  */
27299     case BIND_EXPR:
27300       return *tp;
27301 
27302       /* Treat requires-expressions as dependent. */
27303     case REQUIRES_EXPR:
27304       return *tp;
27305 
27306     case CALL_EXPR:
27307       /* Treat concept checks as dependent. */
27308       if (concept_check_p (*tp))
27309         return *tp;
27310       break;
27311 
27312     case TEMPLATE_ID_EXPR:
27313       /* Treat concept checks as dependent.  */
27314       if (concept_check_p (*tp))
27315 	return *tp;
27316       break;
27317 
27318     case CONSTRUCTOR:
27319       if (CONSTRUCTOR_IS_DEPENDENT (*tp))
27320 	return *tp;
27321       break;
27322 
27323     default:
27324       break;
27325     }
27326 
27327   if (type_dependent_expression_p (*tp))
27328     return *tp;
27329   else
27330     return NULL_TREE;
27331 }
27332 
27333 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
27334    sense defined by the ABI:
27335 
27336    "An expression is instantiation-dependent if it is type-dependent
27337    or value-dependent, or it has a subexpression that is type-dependent
27338    or value-dependent."
27339 
27340    Except don't actually check value-dependence for unevaluated expressions,
27341    because in sizeof(i) we don't care about the value of i.  Checking
27342    type-dependence will in turn check value-dependence of array bounds/template
27343    arguments as needed.  */
27344 
27345 bool
instantiation_dependent_uneval_expression_p(tree expression)27346 instantiation_dependent_uneval_expression_p (tree expression)
27347 {
27348   tree result;
27349 
27350   if (!processing_template_decl)
27351     return false;
27352 
27353   if (expression == error_mark_node)
27354     return false;
27355 
27356   result = cp_walk_tree_without_duplicates (&expression,
27357 					    instantiation_dependent_r, NULL);
27358   return result != NULL_TREE;
27359 }
27360 
27361 /* As above, but also check value-dependence of the expression as a whole.  */
27362 
27363 bool
instantiation_dependent_expression_p(tree expression)27364 instantiation_dependent_expression_p (tree expression)
27365 {
27366   return (instantiation_dependent_uneval_expression_p (expression)
27367 	  || value_dependent_expression_p (expression));
27368 }
27369 
27370 /* Like type_dependent_expression_p, but it also works while not processing
27371    a template definition, i.e. during substitution or mangling.  */
27372 
27373 bool
type_dependent_expression_p_push(tree expr)27374 type_dependent_expression_p_push (tree expr)
27375 {
27376   bool b;
27377   ++processing_template_decl;
27378   b = type_dependent_expression_p (expr);
27379   --processing_template_decl;
27380   return b;
27381 }
27382 
27383 /* Returns TRUE if ARGS contains a type-dependent expression.  */
27384 
27385 bool
any_type_dependent_arguments_p(const vec<tree,va_gc> * args)27386 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
27387 {
27388   unsigned int i;
27389   tree arg;
27390 
27391   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
27392     {
27393       if (type_dependent_expression_p (arg))
27394 	return true;
27395     }
27396   return false;
27397 }
27398 
27399 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
27400    expressions) contains any type-dependent expressions.  */
27401 
27402 bool
any_type_dependent_elements_p(const_tree list)27403 any_type_dependent_elements_p (const_tree list)
27404 {
27405   for (; list; list = TREE_CHAIN (list))
27406     if (type_dependent_expression_p (TREE_VALUE (list)))
27407       return true;
27408 
27409   return false;
27410 }
27411 
27412 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
27413    expressions) contains any value-dependent expressions.  */
27414 
27415 bool
any_value_dependent_elements_p(const_tree list)27416 any_value_dependent_elements_p (const_tree list)
27417 {
27418   for (; list; list = TREE_CHAIN (list))
27419     if (value_dependent_expression_p (TREE_VALUE (list)))
27420       return true;
27421 
27422   return false;
27423 }
27424 
27425 /* Returns TRUE if the ARG (a template argument) is dependent.  */
27426 
27427 bool
dependent_template_arg_p(tree arg)27428 dependent_template_arg_p (tree arg)
27429 {
27430   if (!processing_template_decl)
27431     return false;
27432 
27433   /* Assume a template argument that was wrongly written by the user
27434      is dependent. This is consistent with what
27435      any_dependent_template_arguments_p [that calls this function]
27436      does.  */
27437   if (!arg || arg == error_mark_node)
27438     return true;
27439 
27440   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
27441     arg = argument_pack_select_arg (arg);
27442 
27443   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
27444     return true;
27445   if (TREE_CODE (arg) == TEMPLATE_DECL)
27446     {
27447       if (DECL_TEMPLATE_PARM_P (arg))
27448 	return true;
27449       /* A member template of a dependent class is not necessarily
27450 	 type-dependent, but it is a dependent template argument because it
27451 	 will be a member of an unknown specialization to that template.  */
27452       tree scope = CP_DECL_CONTEXT (arg);
27453       return TYPE_P (scope) && dependent_type_p (scope);
27454     }
27455   else if (ARGUMENT_PACK_P (arg))
27456     {
27457       tree args = ARGUMENT_PACK_ARGS (arg);
27458       int i, len = TREE_VEC_LENGTH (args);
27459       for (i = 0; i < len; ++i)
27460         {
27461           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
27462             return true;
27463         }
27464 
27465       return false;
27466     }
27467   else if (TYPE_P (arg))
27468     return dependent_type_p (arg);
27469   else
27470     return value_dependent_expression_p (arg);
27471 }
27472 
27473 /* Returns true if ARGS (a collection of template arguments) contains
27474    any types that require structural equality testing.  */
27475 
27476 bool
any_template_arguments_need_structural_equality_p(tree args)27477 any_template_arguments_need_structural_equality_p (tree args)
27478 {
27479   int i;
27480   int j;
27481 
27482   if (!args)
27483     return false;
27484   if (args == error_mark_node)
27485     return true;
27486 
27487   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27488     {
27489       tree level = TMPL_ARGS_LEVEL (args, i + 1);
27490       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27491 	{
27492 	  tree arg = TREE_VEC_ELT (level, j);
27493 	  tree packed_args = NULL_TREE;
27494 	  int k, len = 1;
27495 
27496 	  if (ARGUMENT_PACK_P (arg))
27497 	    {
27498 	      /* Look inside the argument pack.  */
27499 	      packed_args = ARGUMENT_PACK_ARGS (arg);
27500 	      len = TREE_VEC_LENGTH (packed_args);
27501 	    }
27502 
27503 	  for (k = 0; k < len; ++k)
27504 	    {
27505 	      if (packed_args)
27506 		arg = TREE_VEC_ELT (packed_args, k);
27507 
27508 	      if (error_operand_p (arg))
27509 		return true;
27510 	      else if (TREE_CODE (arg) == TEMPLATE_DECL)
27511 		continue;
27512 	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
27513 		return true;
27514 	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
27515 		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
27516 		return true;
27517 	    }
27518 	}
27519     }
27520 
27521   return false;
27522 }
27523 
27524 /* Returns true if ARGS (a collection of template arguments) contains
27525    any dependent arguments.  */
27526 
27527 bool
any_dependent_template_arguments_p(const_tree args)27528 any_dependent_template_arguments_p (const_tree args)
27529 {
27530   int i;
27531   int j;
27532 
27533   if (!args)
27534     return false;
27535   if (args == error_mark_node)
27536     return true;
27537 
27538   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27539     {
27540       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
27541       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27542 	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
27543 	  return true;
27544     }
27545 
27546   return false;
27547 }
27548 
27549 /* Returns true if ARGS contains any errors.  */
27550 
27551 bool
any_erroneous_template_args_p(const_tree args)27552 any_erroneous_template_args_p (const_tree args)
27553 {
27554   int i;
27555   int j;
27556 
27557   if (args == error_mark_node)
27558     return true;
27559 
27560   if (args && TREE_CODE (args) != TREE_VEC)
27561     {
27562       if (tree ti = get_template_info (args))
27563 	args = TI_ARGS (ti);
27564       else
27565 	args = NULL_TREE;
27566     }
27567 
27568   if (!args)
27569     return false;
27570 
27571   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
27572     {
27573       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
27574       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
27575 	if (error_operand_p (TREE_VEC_ELT (level, j)))
27576 	  return true;
27577     }
27578 
27579   return false;
27580 }
27581 
27582 /* Returns TRUE if the template TMPL is type-dependent.  */
27583 
27584 bool
dependent_template_p(tree tmpl)27585 dependent_template_p (tree tmpl)
27586 {
27587   if (TREE_CODE (tmpl) == OVERLOAD)
27588     {
27589       for (lkp_iterator iter (tmpl); iter; ++iter)
27590 	if (dependent_template_p (*iter))
27591 	  return true;
27592       return false;
27593     }
27594 
27595   /* Template template parameters are dependent.  */
27596   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
27597       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
27598     return true;
27599   /* So are names that have not been looked up.  */
27600   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
27601     return true;
27602   return false;
27603 }
27604 
27605 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
27606 
27607 bool
dependent_template_id_p(tree tmpl,tree args)27608 dependent_template_id_p (tree tmpl, tree args)
27609 {
27610   return (dependent_template_p (tmpl)
27611 	  || any_dependent_template_arguments_p (args));
27612 }
27613 
27614 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
27615    are dependent.  */
27616 
27617 bool
dependent_omp_for_p(tree declv,tree initv,tree condv,tree incrv)27618 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
27619 {
27620   int i;
27621 
27622   if (!processing_template_decl)
27623     return false;
27624 
27625   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
27626     {
27627       tree decl = TREE_VEC_ELT (declv, i);
27628       tree init = TREE_VEC_ELT (initv, i);
27629       tree cond = TREE_VEC_ELT (condv, i);
27630       tree incr = TREE_VEC_ELT (incrv, i);
27631 
27632       if (type_dependent_expression_p (decl)
27633 	  || TREE_CODE (decl) == SCOPE_REF)
27634 	return true;
27635 
27636       if (init && type_dependent_expression_p (init))
27637 	return true;
27638 
27639       if (cond == global_namespace)
27640 	return true;
27641 
27642       if (type_dependent_expression_p (cond))
27643 	return true;
27644 
27645       if (COMPARISON_CLASS_P (cond)
27646 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
27647 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
27648 	return true;
27649 
27650       if (TREE_CODE (incr) == MODOP_EXPR)
27651 	{
27652 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
27653 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
27654 	    return true;
27655 	}
27656       else if (type_dependent_expression_p (incr))
27657 	return true;
27658       else if (TREE_CODE (incr) == MODIFY_EXPR)
27659 	{
27660 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
27661 	    return true;
27662 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
27663 	    {
27664 	      tree t = TREE_OPERAND (incr, 1);
27665 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
27666 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
27667 		return true;
27668 
27669 	      /* If this loop has a class iterator with != comparison
27670 		 with increment other than i++/++i/i--/--i, make sure the
27671 		 increment is constant.  */
27672 	      if (CLASS_TYPE_P (TREE_TYPE (decl))
27673 		  && TREE_CODE (cond) == NE_EXPR)
27674 		{
27675 		  if (TREE_OPERAND (t, 0) == decl)
27676 		    t = TREE_OPERAND (t, 1);
27677 		  else
27678 		    t = TREE_OPERAND (t, 0);
27679 		  if (TREE_CODE (t) != INTEGER_CST)
27680 		    return true;
27681 		}
27682 	    }
27683 	}
27684     }
27685 
27686   return false;
27687 }
27688 
27689 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
27690    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
27691    no such TYPE can be found.  Note that this function peers inside
27692    uninstantiated templates and therefore should be used only in
27693    extremely limited situations.  ONLY_CURRENT_P restricts this
27694    peering to the currently open classes hierarchy (which is required
27695    when comparing types).  */
27696 
27697 tree
resolve_typename_type(tree type,bool only_current_p)27698 resolve_typename_type (tree type, bool only_current_p)
27699 {
27700   tree scope;
27701   tree name;
27702   tree decl;
27703   int quals;
27704   tree pushed_scope;
27705   tree result;
27706 
27707   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
27708 
27709   scope = TYPE_CONTEXT (type);
27710   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
27711   gcc_checking_assert (uses_template_parms (scope));
27712 
27713   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
27714      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
27715      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
27716      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
27717      identifier  of the TYPENAME_TYPE anymore.
27718      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
27719      TYPENAME_TYPE instead, we avoid messing up with a possible
27720      typedef variant case.  */
27721   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
27722 
27723   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
27724      it first before we can figure out what NAME refers to.  */
27725   if (TREE_CODE (scope) == TYPENAME_TYPE)
27726     {
27727       if (TYPENAME_IS_RESOLVING_P (scope))
27728 	/* Given a class template A with a dependent base with nested type C,
27729 	   typedef typename A::C::C C will land us here, as trying to resolve
27730 	   the initial A::C leads to the local C typedef, which leads back to
27731 	   A::C::C.  So we break the recursion now.  */
27732 	return type;
27733       else
27734 	scope = resolve_typename_type (scope, only_current_p);
27735     }
27736   /* If we don't know what SCOPE refers to, then we cannot resolve the
27737      TYPENAME_TYPE.  */
27738   if (!CLASS_TYPE_P (scope))
27739     return type;
27740   /* If this is a typedef, we don't want to look inside (c++/11987).  */
27741   if (typedef_variant_p (type))
27742     return type;
27743   /* If SCOPE isn't the template itself, it will not have a valid
27744      TYPE_FIELDS list.  */
27745   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
27746     /* scope is either the template itself or a compatible instantiation
27747        like X<T>, so look up the name in the original template.  */
27748     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
27749   /* If scope has no fields, it can't be a current instantiation.  Check this
27750      before currently_open_class to avoid infinite recursion (71515).  */
27751   if (!TYPE_FIELDS (scope))
27752     return type;
27753   /* If the SCOPE is not the current instantiation, there's no reason
27754      to look inside it.  */
27755   if (only_current_p && !currently_open_class (scope))
27756     return type;
27757   /* Enter the SCOPE so that name lookup will be resolved as if we
27758      were in the class definition.  In particular, SCOPE will no
27759      longer be considered a dependent type.  */
27760   pushed_scope = push_scope (scope);
27761   /* Look up the declaration.  */
27762   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
27763 			tf_warning_or_error);
27764 
27765   result = NULL_TREE;
27766 
27767   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
27768      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
27769   tree fullname = TYPENAME_TYPE_FULLNAME (type);
27770   if (!decl)
27771     /*nop*/;
27772   else if (identifier_p (fullname)
27773 	   && TREE_CODE (decl) == TYPE_DECL)
27774     {
27775       result = TREE_TYPE (decl);
27776       if (result == error_mark_node)
27777 	result = NULL_TREE;
27778     }
27779   else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
27780 	   && DECL_CLASS_TEMPLATE_P (decl))
27781     {
27782       /* Obtain the template and the arguments.  */
27783       tree tmpl = TREE_OPERAND (fullname, 0);
27784       if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
27785 	{
27786 	  /* We get here with a plain identifier because a previous tentative
27787 	     parse of the nested-name-specifier as part of a ptr-operator saw
27788 	     ::template X<A>.  The use of ::template is necessary in a
27789 	     ptr-operator, but wrong in a declarator-id.
27790 
27791 	     [temp.names]: In a qualified-id of a declarator-id, the keyword
27792 	     template shall not appear at the top level.  */
27793 	  pedwarn (cp_expr_loc_or_input_loc (fullname), OPT_Wpedantic,
27794 		   "keyword %<template%> not allowed in declarator-id");
27795 	  tmpl = decl;
27796 	}
27797       tree args = TREE_OPERAND (fullname, 1);
27798       /* Instantiate the template.  */
27799       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
27800 				      /*entering_scope=*/true,
27801 				      tf_error | tf_user);
27802       if (result == error_mark_node)
27803 	result = NULL_TREE;
27804     }
27805 
27806   /* Leave the SCOPE.  */
27807   if (pushed_scope)
27808     pop_scope (pushed_scope);
27809 
27810   /* If we failed to resolve it, return the original typename.  */
27811   if (!result)
27812     return type;
27813 
27814   /* If lookup found a typename type, resolve that too.  */
27815   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
27816     {
27817       /* Ill-formed programs can cause infinite recursion here, so we
27818 	 must catch that.  */
27819       TYPENAME_IS_RESOLVING_P (result) = 1;
27820       result = resolve_typename_type (result, only_current_p);
27821       TYPENAME_IS_RESOLVING_P (result) = 0;
27822     }
27823 
27824   /* Qualify the resulting type.  */
27825   quals = cp_type_quals (type);
27826   if (quals)
27827     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
27828 
27829   return result;
27830 }
27831 
27832 /* EXPR is an expression which is not type-dependent.  Return a proxy
27833    for EXPR that can be used to compute the types of larger
27834    expressions containing EXPR.  */
27835 
27836 tree
build_non_dependent_expr(tree expr)27837 build_non_dependent_expr (tree expr)
27838 {
27839   tree orig_expr = expr;
27840   tree inner_expr;
27841 
27842   /* When checking, try to get a constant value for all non-dependent
27843      expressions in order to expose bugs in *_dependent_expression_p
27844      and constexpr.  This can affect code generation, see PR70704, so
27845      only do this for -fchecking=2.  */
27846   if (flag_checking > 1
27847       && cxx_dialect >= cxx11
27848       /* Don't do this during nsdmi parsing as it can lead to
27849 	 unexpected recursive instantiations.  */
27850       && !parsing_nsdmi ()
27851       /* Don't do this during concept processing either and for
27852          the same reason.  */
27853       && !processing_constraint_expression_p ())
27854     fold_non_dependent_expr (expr, tf_none);
27855 
27856   STRIP_ANY_LOCATION_WRAPPER (expr);
27857 
27858   /* Preserve OVERLOADs; the functions must be available to resolve
27859      types.  */
27860   inner_expr = expr;
27861   if (TREE_CODE (inner_expr) == STMT_EXPR)
27862     inner_expr = stmt_expr_value_expr (inner_expr);
27863   if (TREE_CODE (inner_expr) == ADDR_EXPR)
27864     inner_expr = TREE_OPERAND (inner_expr, 0);
27865   if (TREE_CODE (inner_expr) == COMPONENT_REF)
27866     inner_expr = TREE_OPERAND (inner_expr, 1);
27867   if (is_overloaded_fn (inner_expr)
27868       || TREE_CODE (inner_expr) == OFFSET_REF)
27869     return orig_expr;
27870   /* There is no need to return a proxy for a variable or enumerator.  */
27871   if (VAR_P (expr) || TREE_CODE (expr) == CONST_DECL)
27872     return orig_expr;
27873   /* Preserve string constants; conversions from string constants to
27874      "char *" are allowed, even though normally a "const char *"
27875      cannot be used to initialize a "char *".  */
27876   if (TREE_CODE (expr) == STRING_CST)
27877     return orig_expr;
27878   /* Preserve void and arithmetic constants, as an optimization -- there is no
27879      reason to create a new node.  */
27880   if (TREE_CODE (expr) == VOID_CST
27881       || TREE_CODE (expr) == INTEGER_CST
27882       || TREE_CODE (expr) == REAL_CST)
27883     return orig_expr;
27884   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
27885      There is at least one place where we want to know that a
27886      particular expression is a throw-expression: when checking a ?:
27887      expression, there are special rules if the second or third
27888      argument is a throw-expression.  */
27889   if (TREE_CODE (expr) == THROW_EXPR)
27890     return orig_expr;
27891 
27892   /* Don't wrap an initializer list, we need to be able to look inside.  */
27893   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
27894     return orig_expr;
27895 
27896   /* Don't wrap a dummy object, we need to be able to test for it.  */
27897   if (is_dummy_object (expr))
27898     return orig_expr;
27899 
27900   if (TREE_CODE (expr) == COND_EXPR)
27901     return build3 (COND_EXPR,
27902 		   TREE_TYPE (expr),
27903 		   build_non_dependent_expr (TREE_OPERAND (expr, 0)),
27904 		   (TREE_OPERAND (expr, 1)
27905 		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
27906 		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
27907 		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
27908   if (TREE_CODE (expr) == COMPOUND_EXPR
27909       && !COMPOUND_EXPR_OVERLOADED (expr))
27910     return build2 (COMPOUND_EXPR,
27911 		   TREE_TYPE (expr),
27912 		   TREE_OPERAND (expr, 0),
27913 		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
27914 
27915   /* If the type is unknown, it can't really be non-dependent */
27916   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
27917 
27918   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
27919   return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
27920 		     TREE_TYPE (expr), expr);
27921 }
27922 
27923 /* ARGS is a vector of expressions as arguments to a function call.
27924    Replace the arguments with equivalent non-dependent expressions.
27925    This modifies ARGS in place.  */
27926 
27927 void
make_args_non_dependent(vec<tree,va_gc> * args)27928 make_args_non_dependent (vec<tree, va_gc> *args)
27929 {
27930   unsigned int ix;
27931   tree arg;
27932 
27933   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
27934     {
27935       tree newarg = build_non_dependent_expr (arg);
27936       if (newarg != arg)
27937 	(*args)[ix] = newarg;
27938     }
27939 }
27940 
27941 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
27942    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
27943    parms.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
27944 
27945 static tree
make_auto_1(tree name,bool set_canonical)27946 make_auto_1 (tree name, bool set_canonical)
27947 {
27948   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
27949   TYPE_NAME (au) = build_decl (input_location, TYPE_DECL, name, au);
27950   TYPE_STUB_DECL (au) = TYPE_NAME (au);
27951   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
27952     (0, processing_template_decl + 1, processing_template_decl + 1,
27953      TYPE_NAME (au), NULL_TREE);
27954   if (set_canonical)
27955     TYPE_CANONICAL (au) = canonical_type_parameter (au);
27956   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
27957   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
27958   if (name == decltype_auto_identifier)
27959     AUTO_IS_DECLTYPE (au) = true;
27960 
27961   return au;
27962 }
27963 
27964 tree
make_decltype_auto(void)27965 make_decltype_auto (void)
27966 {
27967   return make_auto_1 (decltype_auto_identifier, true);
27968 }
27969 
27970 tree
make_auto(void)27971 make_auto (void)
27972 {
27973   return make_auto_1 (auto_identifier, true);
27974 }
27975 
27976 /* Return a C++17 deduction placeholder for class template TMPL.  */
27977 
27978 tree
make_template_placeholder(tree tmpl)27979 make_template_placeholder (tree tmpl)
27980 {
27981   tree t = make_auto_1 (auto_identifier, false);
27982   CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
27983   /* Our canonical type depends on the placeholder.  */
27984   TYPE_CANONICAL (t) = canonical_type_parameter (t);
27985   return t;
27986 }
27987 
27988 /* True iff T is a C++17 class template deduction placeholder.  */
27989 
27990 bool
template_placeholder_p(tree t)27991 template_placeholder_p (tree t)
27992 {
27993   return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
27994 }
27995 
27996 /* Make a "constrained auto" type-specifier. This is an auto or
27997   decltype(auto) type with constraints that must be associated after
27998   deduction.  The constraint is formed from the given concept CON
27999   and its optional sequence of template arguments ARGS.
28000 
28001   TYPE must be the result of make_auto_type or make_decltype_auto_type. */
28002 
28003 static tree
make_constrained_placeholder_type(tree type,tree con,tree args)28004 make_constrained_placeholder_type (tree type, tree con, tree args)
28005 {
28006   /* Build the constraint. */
28007   tree tmpl = DECL_TI_TEMPLATE (con);
28008   tree expr = tmpl;
28009   if (TREE_CODE (con) == FUNCTION_DECL)
28010     expr = ovl_make (tmpl);
28011   ++processing_template_decl;
28012   expr = build_concept_check (expr, type, args, tf_warning_or_error);
28013   --processing_template_decl;
28014 
28015   PLACEHOLDER_TYPE_CONSTRAINTS (type) = expr;
28016 
28017   /* Our canonical type depends on the constraint.  */
28018   TYPE_CANONICAL (type) = canonical_type_parameter (type);
28019 
28020   /* Attach the constraint to the type declaration. */
28021   return TYPE_NAME (type);
28022 }
28023 
28024 /* Make a "constrained auto" type-specifier.  */
28025 
28026 tree
make_constrained_auto(tree con,tree args)28027 make_constrained_auto (tree con, tree args)
28028 {
28029   tree type = make_auto_1 (auto_identifier, false);
28030   return make_constrained_placeholder_type (type, con, args);
28031 }
28032 
28033 /* Make a "constrained decltype(auto)" type-specifier.  */
28034 
28035 tree
make_constrained_decltype_auto(tree con,tree args)28036 make_constrained_decltype_auto (tree con, tree args)
28037 {
28038   tree type = make_auto_1 (decltype_auto_identifier, false);
28039   return make_constrained_placeholder_type (type, con, args);
28040 }
28041 
28042 /* Build and return a concept definition. Like other templates, the
28043    CONCEPT_DECL node is wrapped by a TEMPLATE_DECL.  This returns the
28044    the TEMPLATE_DECL. */
28045 
28046 tree
finish_concept_definition(cp_expr id,tree init)28047 finish_concept_definition (cp_expr id, tree init)
28048 {
28049   gcc_assert (identifier_p (id));
28050   gcc_assert (processing_template_decl);
28051 
28052   location_t loc = id.get_location();
28053 
28054   /* A concept-definition shall not have associated constraints.  */
28055   if (TEMPLATE_PARMS_CONSTRAINTS (current_template_parms))
28056     {
28057       error_at (loc, "a concept cannot be constrained");
28058       TEMPLATE_PARMS_CONSTRAINTS (current_template_parms) = NULL_TREE;
28059     }
28060 
28061   /* A concept-definition shall appear in namespace scope.  Templates
28062      aren't allowed in block scope, so we only need to check for class
28063      scope.  */
28064   if (TYPE_P (current_scope()) || !DECL_NAMESPACE_SCOPE_P (current_scope ()))
28065     {
28066       error_at (loc, "concept %qE not in namespace scope", *id);
28067       return error_mark_node;
28068     }
28069 
28070   /* Initially build the concept declaration; it's type is bool.  */
28071   tree decl = build_lang_decl_loc (loc, CONCEPT_DECL, *id, boolean_type_node);
28072   DECL_CONTEXT (decl) = current_scope ();
28073   DECL_INITIAL (decl) = init;
28074 
28075   /* Push the enclosing template.  */
28076   return push_template_decl (decl);
28077 }
28078 
28079 /* Given type ARG, return std::initializer_list<ARG>.  */
28080 
28081 static tree
listify(tree arg)28082 listify (tree arg)
28083 {
28084   tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
28085 
28086   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
28087     {
28088       gcc_rich_location richloc (input_location);
28089       maybe_add_include_fixit (&richloc, "<initializer_list>", false);
28090       error_at (&richloc,
28091 		"deducing from brace-enclosed initializer list"
28092 		" requires %<#include <initializer_list>%>");
28093 
28094       return error_mark_node;
28095     }
28096   tree argvec = make_tree_vec (1);
28097   TREE_VEC_ELT (argvec, 0) = arg;
28098 
28099   return lookup_template_class (std_init_list, argvec, NULL_TREE,
28100 				NULL_TREE, 0, tf_warning_or_error);
28101 }
28102 
28103 /* Replace auto in TYPE with std::initializer_list<auto>.  */
28104 
28105 static tree
listify_autos(tree type,tree auto_node)28106 listify_autos (tree type, tree auto_node)
28107 {
28108   tree init_auto = listify (strip_top_quals (auto_node));
28109   tree argvec = make_tree_vec (1);
28110   TREE_VEC_ELT (argvec, 0) = init_auto;
28111   if (processing_template_decl)
28112     argvec = add_to_template_args (current_template_args (), argvec);
28113   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
28114 }
28115 
28116 /* Hash traits for hashing possibly constrained 'auto'
28117    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
28118 
28119 struct auto_hash : default_hash_traits<tree>
28120 {
28121   static inline hashval_t hash (tree);
28122   static inline bool equal (tree, tree);
28123 };
28124 
28125 /* Hash the 'auto' T.  */
28126 
28127 inline hashval_t
hash(tree t)28128 auto_hash::hash (tree t)
28129 {
28130   if (tree c = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (t)))
28131     /* Matching constrained-type-specifiers denote the same template
28132        parameter, so hash the constraint.  */
28133     return hash_placeholder_constraint (c);
28134   else
28135     /* But unconstrained autos are all separate, so just hash the pointer.  */
28136     return iterative_hash_object (t, 0);
28137 }
28138 
28139 /* Compare two 'auto's.  */
28140 
28141 inline bool
equal(tree t1,tree t2)28142 auto_hash::equal (tree t1, tree t2)
28143 {
28144   if (t1 == t2)
28145     return true;
28146 
28147   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
28148   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
28149 
28150   /* Two unconstrained autos are distinct.  */
28151   if (!c1 || !c2)
28152     return false;
28153 
28154   return equivalent_placeholder_constraints (c1, c2);
28155 }
28156 
28157 /* for_each_template_parm callback for extract_autos: if t is a (possibly
28158    constrained) auto, add it to the vector.  */
28159 
28160 static int
extract_autos_r(tree t,void * data)28161 extract_autos_r (tree t, void *data)
28162 {
28163   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
28164   if (is_auto (t))
28165     {
28166       /* All the autos were built with index 0; fix that up now.  */
28167       tree *p = hash.find_slot (t, INSERT);
28168       unsigned idx;
28169       if (*p)
28170 	/* If this is a repeated constrained-type-specifier, use the index we
28171 	   chose before.  */
28172 	idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
28173       else
28174 	{
28175 	  /* Otherwise this is new, so use the current count.  */
28176 	  *p = t;
28177 	  idx = hash.elements () - 1;
28178 	}
28179       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
28180     }
28181 
28182   /* Always keep walking.  */
28183   return 0;
28184 }
28185 
28186 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
28187    says they can appear anywhere in the type.  */
28188 
28189 static tree
extract_autos(tree type)28190 extract_autos (tree type)
28191 {
28192   hash_set<tree> visited;
28193   hash_table<auto_hash> hash (2);
28194 
28195   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
28196 
28197   tree tree_vec = make_tree_vec (hash.elements());
28198   for (hash_table<auto_hash>::iterator iter = hash.begin();
28199        iter != hash.end(); ++iter)
28200     {
28201       tree elt = *iter;
28202       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
28203       TREE_VEC_ELT (tree_vec, i)
28204 	= build_tree_list (NULL_TREE, TYPE_NAME (elt));
28205     }
28206 
28207   return tree_vec;
28208 }
28209 
28210 /* The stem for deduction guide names.  */
28211 const char *const dguide_base = "__dguide_";
28212 
28213 /* Return the name for a deduction guide for class template TMPL.  */
28214 
28215 tree
dguide_name(tree tmpl)28216 dguide_name (tree tmpl)
28217 {
28218   tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
28219   tree tname = TYPE_IDENTIFIER (type);
28220   char *buf = (char *) alloca (1 + strlen (dguide_base)
28221 			       + IDENTIFIER_LENGTH (tname));
28222   memcpy (buf, dguide_base, strlen (dguide_base));
28223   memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
28224 	  IDENTIFIER_LENGTH (tname) + 1);
28225   tree dname = get_identifier (buf);
28226   TREE_TYPE (dname) = type;
28227   return dname;
28228 }
28229 
28230 /* True if NAME is the name of a deduction guide.  */
28231 
28232 bool
dguide_name_p(tree name)28233 dguide_name_p (tree name)
28234 {
28235   return (TREE_CODE (name) == IDENTIFIER_NODE
28236 	  && TREE_TYPE (name)
28237 	  && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
28238 		       strlen (dguide_base)));
28239 }
28240 
28241 /* True if FN is a deduction guide.  */
28242 
28243 bool
deduction_guide_p(const_tree fn)28244 deduction_guide_p (const_tree fn)
28245 {
28246   if (DECL_P (fn))
28247     if (tree name = DECL_NAME (fn))
28248       return dguide_name_p (name);
28249   return false;
28250 }
28251 
28252 /* True if FN is the copy deduction guide, i.e. A(A)->A.  */
28253 
28254 bool
copy_guide_p(const_tree fn)28255 copy_guide_p (const_tree fn)
28256 {
28257   gcc_assert (deduction_guide_p (fn));
28258   if (!DECL_ARTIFICIAL (fn))
28259     return false;
28260   tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
28261   return (TREE_CHAIN (parms) == void_list_node
28262 	  && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
28263 }
28264 
28265 /* True if FN is a guide generated from a constructor template.  */
28266 
28267 bool
template_guide_p(const_tree fn)28268 template_guide_p (const_tree fn)
28269 {
28270   gcc_assert (deduction_guide_p (fn));
28271   if (!DECL_ARTIFICIAL (fn))
28272     return false;
28273   tree tmpl = DECL_TI_TEMPLATE (fn);
28274   if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
28275     return PRIMARY_TEMPLATE_P (org);
28276   return false;
28277 }
28278 
28279 /* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
28280    LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
28281    template parameter types.  Note that the handling of template template
28282    parameters relies on current_template_parms being set appropriately for the
28283    new template.  */
28284 
28285 static tree
rewrite_template_parm(tree olddecl,unsigned index,unsigned level,tree tsubst_args,tsubst_flags_t complain)28286 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
28287 		       tree tsubst_args, tsubst_flags_t complain)
28288 {
28289   if (olddecl == error_mark_node)
28290     return error_mark_node;
28291 
28292   tree oldidx = get_template_parm_index (olddecl);
28293 
28294   tree newtype;
28295   if (TREE_CODE (olddecl) == TYPE_DECL
28296       || TREE_CODE (olddecl) == TEMPLATE_DECL)
28297     {
28298       tree oldtype = TREE_TYPE (olddecl);
28299       newtype = cxx_make_type (TREE_CODE (oldtype));
28300       TYPE_MAIN_VARIANT (newtype) = newtype;
28301       if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
28302 	TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
28303 	  = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
28304     }
28305   else
28306     {
28307       newtype = TREE_TYPE (olddecl);
28308       if (type_uses_auto (newtype))
28309 	{
28310 	  // Substitute once to fix references to other template parameters.
28311 	  newtype = tsubst (newtype, tsubst_args,
28312 			    complain|tf_partial, NULL_TREE);
28313 	  // Now substitute again to reduce the level of the auto.
28314 	  newtype = tsubst (newtype, current_template_args (),
28315 			    complain, NULL_TREE);
28316 	}
28317       else
28318 	newtype = tsubst (newtype, tsubst_args,
28319 			  complain, NULL_TREE);
28320     }
28321 
28322   tree newdecl
28323     = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
28324 		  DECL_NAME (olddecl), newtype);
28325   SET_DECL_TEMPLATE_PARM_P (newdecl);
28326 
28327   tree newidx;
28328   if (TREE_CODE (olddecl) == TYPE_DECL
28329       || TREE_CODE (olddecl) == TEMPLATE_DECL)
28330     {
28331       newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
28332 	= build_template_parm_index (index, level, level,
28333 				     newdecl, newtype);
28334       TEMPLATE_PARM_PARAMETER_PACK (newidx)
28335 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
28336       TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
28337       if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (olddecl)))
28338 	SET_TYPE_STRUCTURAL_EQUALITY (newtype);
28339       else
28340 	TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
28341 
28342       if (TREE_CODE (olddecl) == TEMPLATE_DECL)
28343 	{
28344 	  DECL_TEMPLATE_RESULT (newdecl)
28345 	    = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
28346 			  DECL_NAME (olddecl), newtype);
28347 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
28348 	  // First create a copy (ttargs) of tsubst_args with an
28349 	  // additional level for the template template parameter's own
28350 	  // template parameters (ttparms).
28351 	  tree ttparms = (INNERMOST_TEMPLATE_PARMS
28352 			  (DECL_TEMPLATE_PARMS (olddecl)));
28353 	  const int depth = TMPL_ARGS_DEPTH (tsubst_args);
28354 	  tree ttargs = make_tree_vec (depth + 1);
28355 	  for (int i = 0; i < depth; ++i)
28356 	    TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
28357 	  TREE_VEC_ELT (ttargs, depth)
28358 	    = template_parms_level_to_args (ttparms);
28359 	  // Substitute ttargs into ttparms to fix references to
28360 	  // other template parameters.
28361 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
28362 						 complain|tf_partial);
28363 	  // Now substitute again with args based on tparms, to reduce
28364 	  // the level of the ttparms.
28365 	  ttargs = current_template_args ();
28366 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
28367 						 complain);
28368 	  // Finally, tack the adjusted parms onto tparms.
28369 	  ttparms = tree_cons (size_int (depth), ttparms,
28370 			       current_template_parms);
28371 	  DECL_TEMPLATE_PARMS (newdecl) = ttparms;
28372 	}
28373     }
28374   else
28375     {
28376       tree oldconst = TEMPLATE_PARM_DECL (oldidx);
28377       tree newconst
28378 	= build_decl (DECL_SOURCE_LOCATION (oldconst),
28379 		      TREE_CODE (oldconst),
28380 		      DECL_NAME (oldconst), newtype);
28381       TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
28382 	= TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
28383       SET_DECL_TEMPLATE_PARM_P (newconst);
28384       newidx = build_template_parm_index (index, level, level,
28385 					  newconst, newtype);
28386       TEMPLATE_PARM_PARAMETER_PACK (newidx)
28387 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
28388       DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
28389     }
28390 
28391   return newdecl;
28392 }
28393 
28394 /* As rewrite_template_parm, but for the whole TREE_LIST representing a
28395    template parameter.  */
28396 
28397 static tree
rewrite_tparm_list(tree oldelt,unsigned index,unsigned level,tree targs,unsigned targs_index,tsubst_flags_t complain)28398 rewrite_tparm_list (tree oldelt, unsigned index, unsigned level,
28399 		    tree targs, unsigned targs_index, tsubst_flags_t complain)
28400 {
28401   tree olddecl = TREE_VALUE (oldelt);
28402   tree newdecl = rewrite_template_parm (olddecl, index, level,
28403 					targs, complain);
28404   if (newdecl == error_mark_node)
28405     return error_mark_node;
28406   tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
28407 				     targs, complain, NULL_TREE);
28408   tree list = build_tree_list (newdef, newdecl);
28409   TEMPLATE_PARM_CONSTRAINTS (list)
28410     = tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
28411 			      targs, complain, NULL_TREE);
28412   int depth = TMPL_ARGS_DEPTH (targs);
28413   TMPL_ARG (targs, depth, targs_index) = template_parm_to_arg (list);
28414   return list;
28415 }
28416 
28417 /* Returns a C++17 class deduction guide template based on the constructor
28418    CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
28419    guide, REFERENCE_TYPE for an implicit copy/move guide, or TREE_LIST for an
28420    aggregate initialization guide.  */
28421 
28422 static tree
build_deduction_guide(tree type,tree ctor,tree outer_args,tsubst_flags_t complain)28423 build_deduction_guide (tree type, tree ctor, tree outer_args, tsubst_flags_t complain)
28424 {
28425   tree tparms, targs, fparms, fargs, ci;
28426   bool memtmpl = false;
28427   bool explicit_p;
28428   location_t loc;
28429   tree fn_tmpl = NULL_TREE;
28430 
28431   if (outer_args)
28432     {
28433       ++processing_template_decl;
28434       type = tsubst (type, outer_args, complain, CLASSTYPE_TI_TEMPLATE (type));
28435       --processing_template_decl;
28436     }
28437 
28438   if (!DECL_DECLARES_FUNCTION_P (ctor))
28439     {
28440       if (TYPE_P (ctor))
28441 	{
28442 	  bool copy_p = TYPE_REF_P (ctor);
28443 	  if (copy_p)
28444 	    fparms = tree_cons (NULL_TREE, type, void_list_node);
28445 	  else
28446 	    fparms = void_list_node;
28447 	}
28448       else if (TREE_CODE (ctor) == TREE_LIST)
28449 	fparms = ctor;
28450       else
28451 	gcc_unreachable ();
28452 
28453       tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
28454       tparms = DECL_TEMPLATE_PARMS (ctmpl);
28455       targs = CLASSTYPE_TI_ARGS (type);
28456       ci = NULL_TREE;
28457       fargs = NULL_TREE;
28458       loc = DECL_SOURCE_LOCATION (ctmpl);
28459       explicit_p = false;
28460     }
28461   else
28462     {
28463       ++processing_template_decl;
28464       bool ok = true;
28465 
28466       fn_tmpl
28467 	= (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
28468 	   : DECL_TI_TEMPLATE (ctor));
28469       if (outer_args)
28470 	fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
28471       ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
28472 
28473       tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
28474       /* If type is a member class template, DECL_TI_ARGS (ctor) will have
28475 	 fully specialized args for the enclosing class.  Strip those off, as
28476 	 the deduction guide won't have those template parameters.  */
28477       targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
28478 						TMPL_PARMS_DEPTH (tparms));
28479       /* Discard the 'this' parameter.  */
28480       fparms = FUNCTION_ARG_CHAIN (ctor);
28481       fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
28482       ci = get_constraints (ctor);
28483       loc = DECL_SOURCE_LOCATION (ctor);
28484       explicit_p = DECL_NONCONVERTING_P (ctor);
28485 
28486       if (PRIMARY_TEMPLATE_P (fn_tmpl))
28487 	{
28488 	  memtmpl = true;
28489 
28490 	  /* For a member template constructor, we need to flatten the two
28491 	     template parameter lists into one, and then adjust the function
28492 	     signature accordingly.  This gets...complicated.  */
28493 	  tree save_parms = current_template_parms;
28494 
28495 	  /* For a member template we should have two levels of parms/args, one
28496 	     for the class and one for the constructor.  We stripped
28497 	     specialized args for further enclosing classes above.  */
28498 	  const int depth = 2;
28499 	  gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
28500 
28501 	  /* Template args for translating references to the two-level template
28502 	     parameters into references to the one-level template parameters we
28503 	     are creating.  */
28504 	  tree tsubst_args = copy_node (targs);
28505 	  TMPL_ARGS_LEVEL (tsubst_args, depth)
28506 	    = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
28507 
28508 	  /* Template parms for the constructor template.  */
28509 	  tree ftparms = TREE_VALUE (tparms);
28510 	  unsigned flen = TREE_VEC_LENGTH (ftparms);
28511 	  /* Template parms for the class template.  */
28512 	  tparms = TREE_CHAIN (tparms);
28513 	  tree ctparms = TREE_VALUE (tparms);
28514 	  unsigned clen = TREE_VEC_LENGTH (ctparms);
28515 	  /* Template parms for the deduction guide start as a copy of the
28516 	     template parms for the class.  We set current_template_parms for
28517 	     lookup_template_class_1.  */
28518 	  current_template_parms = tparms = copy_node (tparms);
28519 	  tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
28520 	  for (unsigned i = 0; i < clen; ++i)
28521 	    TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
28522 
28523 	  /* Now we need to rewrite the constructor parms to append them to the
28524 	     class parms.  */
28525 	  for (unsigned i = 0; i < flen; ++i)
28526 	    {
28527 	      unsigned index = i + clen;
28528 	      unsigned level = 1;
28529 	      tree oldelt = TREE_VEC_ELT (ftparms, i);
28530 	      tree newelt
28531 		= rewrite_tparm_list (oldelt, index, level,
28532 				      tsubst_args, i, complain);
28533 	      if (newelt == error_mark_node)
28534 		ok = false;
28535 	      TREE_VEC_ELT (new_vec, index) = newelt;
28536 	    }
28537 
28538 	  /* Now we have a final set of template parms to substitute into the
28539 	     function signature.  */
28540 	  targs = template_parms_to_args (tparms);
28541 	  fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
28542 				     complain, ctor);
28543 	  if (fparms == error_mark_node)
28544 	    ok = false;
28545 	  if (ci)
28546 	    ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
28547 
28548 	  /* Parms are to have DECL_CHAIN tsubsted, which would be skipped if
28549 	     cp_unevaluated_operand.  */
28550 	  cp_evaluated ev;
28551 	  fargs = tsubst (fargs, tsubst_args, complain, ctor);
28552 	  current_template_parms = save_parms;
28553 	}
28554 
28555       --processing_template_decl;
28556       if (!ok)
28557 	return error_mark_node;
28558     }
28559 
28560   if (!memtmpl)
28561     {
28562       /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
28563       tparms = copy_node (tparms);
28564       INNERMOST_TEMPLATE_PARMS (tparms)
28565 	= copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
28566     }
28567 
28568   tree fntype = build_function_type (type, fparms);
28569   tree ded_fn = build_lang_decl_loc (loc,
28570 				     FUNCTION_DECL,
28571 				     dguide_name (type), fntype);
28572   DECL_ARGUMENTS (ded_fn) = fargs;
28573   DECL_ARTIFICIAL (ded_fn) = true;
28574   DECL_NONCONVERTING_P (ded_fn) = explicit_p;
28575   tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
28576   DECL_ARTIFICIAL (ded_tmpl) = true;
28577   DECL_TEMPLATE_RESULT (ded_tmpl) = ded_fn;
28578   TREE_TYPE (ded_tmpl) = TREE_TYPE (ded_fn);
28579   DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
28580   DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
28581   if (DECL_P (ctor))
28582     DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
28583   if (ci)
28584     set_constraints (ded_tmpl, ci);
28585 
28586   return ded_tmpl;
28587 }
28588 
28589 /* Add to LIST the member types for the reshaped initializer CTOR.  */
28590 
28591 static tree
collect_ctor_idx_types(tree ctor,tree list)28592 collect_ctor_idx_types (tree ctor, tree list)
28593 {
28594   vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (ctor);
28595   tree idx, val; unsigned i;
28596   FOR_EACH_CONSTRUCTOR_ELT (v, i, idx, val)
28597     {
28598       if (BRACE_ENCLOSED_INITIALIZER_P (val)
28599 	  && CONSTRUCTOR_NELTS (val))
28600 	if (tree subidx = CONSTRUCTOR_ELT (val, 0)->index)
28601 	  if (TREE_CODE (subidx) == FIELD_DECL)
28602 	    {
28603 	      list = collect_ctor_idx_types (val, list);
28604 	      continue;
28605 	    }
28606       tree ftype = finish_decltype_type (idx, true, tf_none);
28607       list = tree_cons (NULL_TREE, ftype, list);
28608     }
28609 
28610   return list;
28611 }
28612 
28613 /* Return whether ETYPE is, or is derived from, a specialization of TMPL.  */
28614 
28615 static bool
is_spec_or_derived(tree etype,tree tmpl)28616 is_spec_or_derived (tree etype, tree tmpl)
28617 {
28618   if (!etype || !CLASS_TYPE_P (etype))
28619     return false;
28620 
28621   tree type = TREE_TYPE (tmpl);
28622   tree tparms = (INNERMOST_TEMPLATE_PARMS
28623 		 (DECL_TEMPLATE_PARMS (tmpl)));
28624   tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
28625   int err = unify (tparms, targs, type, etype,
28626 		   UNIFY_ALLOW_DERIVED, /*explain*/false);
28627   ggc_free (targs);
28628   return !err;
28629 }
28630 
28631 /* Return a C++20 aggregate deduction candidate for TYPE initialized from
28632    INIT.  */
28633 
28634 static tree
maybe_aggr_guide(tree tmpl,tree init,vec<tree,va_gc> * args)28635 maybe_aggr_guide (tree tmpl, tree init, vec<tree,va_gc> *args)
28636 {
28637   if (cxx_dialect < cxx2a)
28638     return NULL_TREE;
28639 
28640   if (init == NULL_TREE)
28641     return NULL_TREE;
28642 
28643   tree type = TREE_TYPE (tmpl);
28644   if (!CP_AGGREGATE_TYPE_P (type))
28645     return NULL_TREE;
28646 
28647   /* No aggregate candidate for copy-initialization.  */
28648   if (args->length() == 1)
28649     {
28650       tree val = (*args)[0];
28651       if (is_spec_or_derived (tmpl, TREE_TYPE (val)))
28652 	return NULL_TREE;
28653     }
28654 
28655   /* If we encounter a problem, we just won't add the candidate.  */
28656   tsubst_flags_t complain = tf_none;
28657 
28658   tree parms = NULL_TREE;
28659   if (BRACE_ENCLOSED_INITIALIZER_P (init))
28660     {
28661       init = reshape_init (type, init, complain);
28662       if (init == error_mark_node)
28663 	return NULL_TREE;
28664       parms = collect_ctor_idx_types (init, parms);
28665     }
28666   else if (TREE_CODE (init) == TREE_LIST)
28667     {
28668       int len = list_length (init);
28669       for (tree field = TYPE_FIELDS (type);
28670 	   len;
28671 	   --len, field = DECL_CHAIN (field))
28672 	{
28673 	  field = next_initializable_field (field);
28674 	  if (!field)
28675 	    return NULL_TREE;
28676 	  tree ftype = finish_decltype_type (field, true, complain);
28677 	  parms = tree_cons (NULL_TREE, ftype, parms);
28678 	}
28679     }
28680   else
28681     /* Aggregate initialization doesn't apply to an initializer expression.  */
28682     return NULL_TREE;
28683 
28684   if (parms)
28685     {
28686       tree last = parms;
28687       parms = nreverse (parms);
28688       TREE_CHAIN (last) = void_list_node;
28689       tree guide = build_deduction_guide (type, parms, NULL_TREE, complain);
28690       return guide;
28691     }
28692 
28693   return NULL_TREE;
28694 }
28695 
28696 /* UGUIDES are the deduction guides for the underlying template of alias
28697    template TMPL; adjust them to be deduction guides for TMPL.  */
28698 
28699 static tree
alias_ctad_tweaks(tree tmpl,tree uguides)28700 alias_ctad_tweaks (tree tmpl, tree uguides)
28701 {
28702   /* [over.match.class.deduct]: When resolving a placeholder for a deduced
28703      class type (9.2.8.2) where the template-name names an alias template A,
28704      the defining-type-id of A must be of the form
28705 
28706      typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
28707 
28708      as specified in 9.2.8.2. The guides of A are the set of functions or
28709      function templates formed as follows. For each function or function
28710      template f in the guides of the template named by the simple-template-id
28711      of the defining-type-id, the template arguments of the return type of f
28712      are deduced from the defining-type-id of A according to the process in
28713      13.10.2.5 with the exception that deduction does not fail if not all
28714      template arguments are deduced. Let g denote the result of substituting
28715      these deductions into f. If substitution succeeds, form a function or
28716      function template f' with the following properties and add it to the set
28717      of guides of A:
28718 
28719      * The function type of f' is the function type of g.
28720 
28721      * If f is a function template, f' is a function template whose template
28722      parameter list consists of all the template parameters of A (including
28723      their default template arguments) that appear in the above deductions or
28724      (recursively) in their default template arguments, followed by the
28725      template parameters of f that were not deduced (including their default
28726      template arguments), otherwise f' is not a function template.
28727 
28728      * The associated constraints (13.5.2) are the conjunction of the
28729      associated constraints of g and a constraint that is satisfied if and only
28730      if the arguments of A are deducible (see below) from the return type.
28731 
28732      * If f is a copy deduction candidate (12.4.1.8), then f' is considered to
28733      be so as well.
28734 
28735      * If f was generated from a deduction-guide (12.4.1.8), then f' is
28736      considered to be so as well.
28737 
28738      * The explicit-specifier of f' is the explicit-specifier of g (if
28739      any).  */
28740 
28741   /* This implementation differs from the above in two significant ways:
28742 
28743      1) We include all template parameters of A, not just some.
28744      2) The added constraint is same_type instead of deducible.
28745 
28746      I believe that while it's probably possible to construct a testcase that
28747      behaves differently with this simplification, it should have the same
28748      effect for real uses.  Including all template parameters means that we
28749      deduce all parameters of A when resolving the call, so when we're in the
28750      constraint we don't need to deduce them again, we can just check whether
28751      the deduction produced the desired result.  */
28752 
28753   tsubst_flags_t complain = tf_warning_or_error;
28754   tree atype = TREE_TYPE (tmpl);
28755   tree aguides = NULL_TREE;
28756   tree atparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
28757   unsigned natparms = TREE_VEC_LENGTH (atparms);
28758   tree utype = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
28759   for (ovl_iterator iter (uguides); iter; ++iter)
28760     {
28761       tree f = *iter;
28762       tree in_decl = f;
28763       location_t loc = DECL_SOURCE_LOCATION (f);
28764       tree ret = TREE_TYPE (TREE_TYPE (f));
28765       tree fprime = f;
28766       if (TREE_CODE (f) == TEMPLATE_DECL)
28767 	{
28768 	  processing_template_decl_sentinel ptds (/*reset*/false);
28769 	  ++processing_template_decl;
28770 
28771 	  /* Deduce template arguments for f from the type-id of A.  */
28772 	  tree ftparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (f));
28773 	  unsigned len = TREE_VEC_LENGTH (ftparms);
28774 	  tree targs = make_tree_vec (len);
28775 	  int err = unify (ftparms, targs, ret, utype, UNIFY_ALLOW_NONE, false);
28776 	  if (err)
28777 	    continue;
28778 
28779 	  /* The number of parms for f' is the number of parms for A plus
28780 	     non-deduced parms of f.  */
28781 	  unsigned ndlen = 0;
28782 	  unsigned j;
28783 	  for (unsigned i = 0; i < len; ++i)
28784 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
28785 	      ++ndlen;
28786 	  tree gtparms = make_tree_vec (natparms + ndlen);
28787 
28788 	  /* First copy over the parms of A.  */
28789 	  for (j = 0; j < natparms; ++j)
28790 	    TREE_VEC_ELT (gtparms, j) = TREE_VEC_ELT (atparms, j);
28791 	  /* Now rewrite the non-deduced parms of f.  */
28792 	  for (unsigned i = 0; ndlen && i < len; ++i)
28793 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
28794 	      {
28795 		--ndlen;
28796 		unsigned index = j++;
28797 		unsigned level = 1;
28798 		tree oldlist = TREE_VEC_ELT (ftparms, i);
28799 		tree list = rewrite_tparm_list (oldlist, index, level,
28800 						targs, i, complain);
28801 		TREE_VEC_ELT (gtparms, index) = list;
28802 	      }
28803 	  gtparms = build_tree_list (size_one_node, gtparms);
28804 
28805 	  /* Substitute the deduced arguments plus the rewritten template
28806 	     parameters into f to get g.  This covers the type, copyness,
28807 	     guideness, and explicit-specifier.  */
28808 	  tree g = tsubst_decl (DECL_TEMPLATE_RESULT (f), targs, complain);
28809 	  if (g == error_mark_node)
28810 	    continue;
28811 	  DECL_USE_TEMPLATE (g) = 0;
28812 	  fprime = build_template_decl (g, gtparms, false);
28813 	  DECL_TEMPLATE_RESULT (fprime) = g;
28814 	  TREE_TYPE (fprime) = TREE_TYPE (g);
28815 	  tree gtargs = template_parms_to_args (gtparms);
28816 	  DECL_TEMPLATE_INFO (g) = build_template_info (fprime, gtargs);
28817 	  DECL_PRIMARY_TEMPLATE (fprime) = fprime;
28818 
28819 	  /* Substitute the associated constraints.  */
28820 	  tree ci = get_constraints (f);
28821 	  if (ci)
28822 	    ci = tsubst_constraint_info (ci, targs, complain, in_decl);
28823 	  if (ci == error_mark_node)
28824 	    continue;
28825 
28826 	  /* Add a constraint that the return type matches the instantiation of
28827 	     A with the same template arguments.  */
28828 	  ret = TREE_TYPE (TREE_TYPE (fprime));
28829 	  if (!same_type_p (atype, ret)
28830 	      /* FIXME this should mean they don't compare as equivalent.  */
28831 	      || dependent_alias_template_spec_p (atype, nt_opaque))
28832 	    {
28833 	      tree same = finish_trait_expr (loc, CPTK_IS_SAME_AS, atype, ret);
28834 	      ci = append_constraint (ci, same);
28835 	    }
28836 
28837 	  if (ci)
28838 	    {
28839 	      remove_constraints (fprime);
28840 	      set_constraints (fprime, ci);
28841 	    }
28842 	}
28843       else
28844 	{
28845 	  /* For a non-template deduction guide, if the arguments of A aren't
28846 	     deducible from the return type, don't add the candidate.  */
28847 	  tree targs = make_tree_vec (natparms);
28848 	  int err = unify (atparms, targs, utype, ret, UNIFY_ALLOW_NONE, false);
28849 	  for (unsigned i = 0; !err && i < natparms; ++i)
28850 	    if (TREE_VEC_ELT (targs, i) == NULL_TREE)
28851 	      err = true;
28852 	  if (err)
28853 	    continue;
28854 	}
28855 
28856       aguides = lookup_add (fprime, aguides);
28857     }
28858 
28859   return aguides;
28860 }
28861 
28862 /* Return artificial deduction guides built from the constructors of class
28863    template TMPL.  */
28864 
28865 static tree
ctor_deduction_guides_for(tree tmpl,tsubst_flags_t complain)28866 ctor_deduction_guides_for (tree tmpl, tsubst_flags_t complain)
28867 {
28868   tree type = TREE_TYPE (tmpl);
28869   tree outer_args = NULL_TREE;
28870   if (DECL_CLASS_SCOPE_P (tmpl)
28871       && CLASSTYPE_TEMPLATE_INSTANTIATION (DECL_CONTEXT (tmpl)))
28872     {
28873       outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
28874       type = TREE_TYPE (most_general_template (tmpl));
28875     }
28876 
28877   tree cands = NULL_TREE;
28878 
28879   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
28880     {
28881       /* Skip inherited constructors.  */
28882       if (iter.using_p ())
28883 	continue;
28884 
28885       tree guide = build_deduction_guide (type, *iter, outer_args, complain);
28886       cands = lookup_add (guide, cands);
28887     }
28888 
28889   /* Add implicit default constructor deduction guide.  */
28890   if (!TYPE_HAS_USER_CONSTRUCTOR (type))
28891     {
28892       tree guide = build_deduction_guide (type, type, outer_args,
28893 					  complain);
28894       cands = lookup_add (guide, cands);
28895     }
28896 
28897   /* Add copy guide.  */
28898   {
28899     tree gtype = build_reference_type (type);
28900     tree guide = build_deduction_guide (type, gtype, outer_args,
28901 					complain);
28902     cands = lookup_add (guide, cands);
28903   }
28904 
28905   return cands;
28906 }
28907 
28908 static GTY((deletable)) hash_map<tree, tree_pair_p> *dguide_cache;
28909 
28910 /* Return the non-aggregate deduction guides for deducible template TMPL.  The
28911    aggregate candidate is added separately because it depends on the
28912    initializer.  Set ANY_DGUIDES_P if we find a non-implicit deduction
28913    guide.  */
28914 
28915 static tree
deduction_guides_for(tree tmpl,bool & any_dguides_p,tsubst_flags_t complain)28916 deduction_guides_for (tree tmpl, bool &any_dguides_p, tsubst_flags_t complain)
28917 {
28918   tree guides = NULL_TREE;
28919   if (DECL_ALIAS_TEMPLATE_P (tmpl))
28920     {
28921       tree under = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
28922       tree tinfo = get_template_info (under);
28923       guides = deduction_guides_for (TI_TEMPLATE (tinfo), any_dguides_p,
28924 				     complain);
28925     }
28926   else
28927     {
28928       guides = lookup_qualified_name (CP_DECL_CONTEXT (tmpl),
28929 				      dguide_name (tmpl),
28930 				      /*type*/false, /*complain*/false,
28931 				      /*hidden*/false);
28932       if (guides == error_mark_node)
28933 	guides = NULL_TREE;
28934       else
28935 	any_dguides_p = true;
28936     }
28937 
28938   /* Cache the deduction guides for a template.  We also remember the result of
28939      lookup, and rebuild everything if it changes; should be very rare.  */
28940   tree_pair_p cache = NULL;
28941   if (tree_pair_p &r
28942       = hash_map_safe_get_or_insert<hm_ggc> (dguide_cache, tmpl))
28943     {
28944       cache = r;
28945       if (cache->purpose == guides)
28946 	return cache->value;
28947     }
28948   else
28949     {
28950       r = cache = ggc_cleared_alloc<tree_pair_s> ();
28951       cache->purpose = guides;
28952     }
28953 
28954   tree cands = NULL_TREE;
28955   if (DECL_ALIAS_TEMPLATE_P (tmpl))
28956     cands = alias_ctad_tweaks (tmpl, guides);
28957   else
28958     {
28959       cands = ctor_deduction_guides_for (tmpl, complain);
28960       for (ovl_iterator it (guides); it; ++it)
28961 	cands = lookup_add (*it, cands);
28962     }
28963 
28964   cache->value = cands;
28965   return cands;
28966 }
28967 
28968 /* Return whether TMPL is a (class template argument-) deducible template.  */
28969 
28970 bool
ctad_template_p(tree tmpl)28971 ctad_template_p (tree tmpl)
28972 {
28973   /* A deducible template is either a class template or is an alias template
28974      whose defining-type-id is of the form
28975 
28976       typename(opt) nested-name-specifier(opt) template(opt) simple-template-id
28977 
28978      where the nested-name-specifier (if any) is non-dependent and the
28979      template-name of the simple-template-id names a deducible template.  */
28980 
28981   if (DECL_CLASS_TEMPLATE_P (tmpl)
28982       || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
28983     return true;
28984   if (!DECL_ALIAS_TEMPLATE_P (tmpl))
28985     return false;
28986   tree orig = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
28987   if (tree tinfo = get_template_info (orig))
28988     return ctad_template_p (TI_TEMPLATE (tinfo));
28989   return false;
28990 }
28991 
28992 /* Deduce template arguments for the class template placeholder PTYPE for
28993    template TMPL based on the initializer INIT, and return the resulting
28994    type.  */
28995 
28996 static tree
do_class_deduction(tree ptype,tree tmpl,tree init,int flags,tsubst_flags_t complain)28997 do_class_deduction (tree ptype, tree tmpl, tree init,
28998 		    int flags, tsubst_flags_t complain)
28999 {
29000   /* We should have handled this in the caller.  */
29001   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
29002     return ptype;
29003 
29004   /* Initializing one placeholder from another.  */
29005   if (init && TREE_CODE (init) == TEMPLATE_PARM_INDEX
29006       && is_auto (TREE_TYPE (init))
29007       && CLASS_PLACEHOLDER_TEMPLATE (TREE_TYPE (init)) == tmpl)
29008     return cp_build_qualified_type (TREE_TYPE (init), cp_type_quals (ptype));
29009 
29010   /* Look through alias templates that just rename another template.  */
29011   tmpl = get_underlying_template (tmpl);
29012   if (!ctad_template_p (tmpl))
29013     {
29014       if (complain & tf_error)
29015 	error ("non-deducible template %qT used without template arguments", tmpl);
29016       return error_mark_node;
29017     }
29018   else if (cxx_dialect < cxx2a && DECL_ALIAS_TEMPLATE_P (tmpl))
29019     {
29020       /* This doesn't affect conforming C++17 code, so just pedwarn.  */
29021       if (complain & tf_warning_or_error)
29022 	pedwarn (input_location, 0, "alias template deduction only available "
29023 		 "with %<-std=c++2a%> or %<-std=gnu++2a%>");
29024     }
29025 
29026   tree type = TREE_TYPE (tmpl);
29027 
29028   bool try_list_ctor = false;
29029 
29030   releasing_vec rv_args = NULL;
29031   vec<tree,va_gc> *&args = *&rv_args;
29032   if (init == NULL_TREE)
29033     args = make_tree_vector ();
29034   else if (BRACE_ENCLOSED_INITIALIZER_P (init))
29035     {
29036       try_list_ctor = TYPE_HAS_LIST_CTOR (type);
29037       if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
29038 	{
29039 	  /* As an exception, the first phase in 16.3.1.7 (considering the
29040 	     initializer list as a single argument) is omitted if the
29041 	     initializer list consists of a single expression of type cv U,
29042 	     where U is a specialization of C or a class derived from a
29043 	     specialization of C.  */
29044 	  tree elt = CONSTRUCTOR_ELT (init, 0)->value;
29045 	  if (is_spec_or_derived (TREE_TYPE (elt), tmpl))
29046 	    try_list_ctor = false;
29047 	}
29048       if (try_list_ctor || is_std_init_list (type))
29049 	args = make_tree_vector_single (init);
29050       else
29051 	args = make_tree_vector_from_ctor (init);
29052     }
29053   else if (TREE_CODE (init) == TREE_LIST)
29054     args = make_tree_vector_from_list (init);
29055   else
29056     args = make_tree_vector_single (init);
29057 
29058   /* Do this now to avoid problems with erroneous args later on.  */
29059   args = resolve_args (args, complain);
29060   if (args == NULL)
29061     return error_mark_node;
29062 
29063   bool any_dguides_p = false;
29064   tree cands = deduction_guides_for (tmpl, any_dguides_p, complain);
29065   if (cands == error_mark_node)
29066     return error_mark_node;
29067 
29068   /* Prune explicit deduction guides in copy-initialization context.  */
29069   bool elided = false;
29070   if (flags & LOOKUP_ONLYCONVERTING)
29071     {
29072       for (lkp_iterator iter (cands); !elided && iter; ++iter)
29073 	if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
29074 	  elided = true;
29075 
29076       if (elided)
29077 	{
29078 	  /* Found a nonconverting guide, prune the candidates.  */
29079 	  tree pruned = NULL_TREE;
29080 	  for (lkp_iterator iter (cands); iter; ++iter)
29081 	    if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
29082 	      pruned = lookup_add (*iter, pruned);
29083 
29084 	  cands = pruned;
29085 	}
29086     }
29087 
29088   if (!any_dguides_p)
29089     if (tree guide = maybe_aggr_guide (tmpl, init, args))
29090       cands = lookup_add (guide, cands);
29091 
29092   tree call = error_mark_node;
29093 
29094   /* If this is list-initialization and the class has a list constructor, first
29095      try deducing from the list as a single argument, as [over.match.list].  */
29096   tree list_cands = NULL_TREE;
29097   if (try_list_ctor && cands)
29098     for (lkp_iterator iter (cands); iter; ++iter)
29099       {
29100 	tree dg = *iter;
29101 	if (is_list_ctor (dg))
29102 	  list_cands = lookup_add (dg, list_cands);
29103       }
29104   if (list_cands)
29105     {
29106       ++cp_unevaluated_operand;
29107       call = build_new_function_call (list_cands, &args, tf_decltype);
29108       --cp_unevaluated_operand;
29109 
29110       if (call == error_mark_node)
29111 	{
29112 	  /* That didn't work, now try treating the list as a sequence of
29113 	     arguments.  */
29114 	  release_tree_vector (args);
29115 	  args = make_tree_vector_from_ctor (init);
29116 	}
29117     }
29118 
29119   if (elided && !cands)
29120     {
29121       error ("cannot deduce template arguments for copy-initialization"
29122 	     " of %qT, as it has no non-explicit deduction guides or "
29123 	     "user-declared constructors", type);
29124       return error_mark_node;
29125     }
29126   else if (!cands && call == error_mark_node)
29127     {
29128       error ("cannot deduce template arguments of %qT, as it has no viable "
29129 	     "deduction guides", type);
29130       return error_mark_node;
29131     }
29132 
29133   if (call == error_mark_node)
29134     {
29135       ++cp_unevaluated_operand;
29136       call = build_new_function_call (cands, &args, tf_decltype);
29137       --cp_unevaluated_operand;
29138     }
29139 
29140   if (call == error_mark_node
29141       && (complain & tf_warning_or_error))
29142     {
29143       error ("class template argument deduction failed:");
29144 
29145       ++cp_unevaluated_operand;
29146       call = build_new_function_call (cands, &args, complain | tf_decltype);
29147       --cp_unevaluated_operand;
29148 
29149       if (elided)
29150 	inform (input_location, "explicit deduction guides not considered "
29151 		"for copy-initialization");
29152     }
29153 
29154   return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
29155 }
29156 
29157 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
29158    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
29159    The CONTEXT determines the context in which auto deduction is performed
29160    and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
29161    OUTER_TARGS are used during template argument deduction
29162    (context == adc_unify) to properly substitute the result, and is ignored
29163    in other contexts.
29164 
29165    For partial-concept-ids, extra args may be appended to the list of deduced
29166    template arguments prior to determining constraint satisfaction.  */
29167 
29168 tree
do_auto_deduction(tree type,tree init,tree auto_node,tsubst_flags_t complain,auto_deduction_context context,tree outer_targs,int flags)29169 do_auto_deduction (tree type, tree init, tree auto_node,
29170                    tsubst_flags_t complain, auto_deduction_context context,
29171 		   tree outer_targs, int flags)
29172 {
29173   tree targs;
29174 
29175   if (init == error_mark_node)
29176     return error_mark_node;
29177 
29178   if (init && type_dependent_expression_p (init)
29179       && context != adc_unify)
29180     /* Defining a subset of type-dependent expressions that we can deduce
29181        from ahead of time isn't worth the trouble.  */
29182     return type;
29183 
29184   /* Similarly, we can't deduce from another undeduced decl.  */
29185   if (init && undeduced_auto_decl (init))
29186     return type;
29187 
29188   /* We may be doing a partial substitution, but we still want to replace
29189      auto_node.  */
29190   complain &= ~tf_partial;
29191 
29192   if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
29193     /* C++17 class template argument deduction.  */
29194     return do_class_deduction (type, tmpl, init, flags, complain);
29195 
29196   if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
29197     /* Nothing we can do with this, even in deduction context.  */
29198     return type;
29199 
29200   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
29201      with either a new invented type template parameter U or, if the
29202      initializer is a braced-init-list (8.5.4), with
29203      std::initializer_list<U>.  */
29204   if (BRACE_ENCLOSED_INITIALIZER_P (init))
29205     {
29206       if (!DIRECT_LIST_INIT_P (init))
29207 	type = listify_autos (type, auto_node);
29208       else if (CONSTRUCTOR_NELTS (init) == 1)
29209 	init = CONSTRUCTOR_ELT (init, 0)->value;
29210       else
29211 	{
29212           if (complain & tf_warning_or_error)
29213             {
29214 	      if (permerror (input_location, "direct-list-initialization of "
29215 			     "%<auto%> requires exactly one element"))
29216 	        inform (input_location,
29217 		        "for deduction to %<std::initializer_list%>, use copy-"
29218 		        "list-initialization (i.e. add %<=%> before the %<{%>)");
29219             }
29220 	  type = listify_autos (type, auto_node);
29221 	}
29222     }
29223 
29224   if (type == error_mark_node)
29225     return error_mark_node;
29226 
29227   init = resolve_nondeduced_context (init, complain);
29228 
29229   if (context == adc_decomp_type
29230       && auto_node == type
29231       && init != error_mark_node
29232       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
29233     /* [dcl.decomp]/1 - if decomposition declaration has no ref-qualifiers
29234        and initializer has array type, deduce cv-qualified array type.  */
29235     return cp_build_qualified_type_real (TREE_TYPE (init), TYPE_QUALS (type),
29236 					 complain);
29237   else if (AUTO_IS_DECLTYPE (auto_node))
29238     {
29239       tree stripped_init = tree_strip_any_location_wrapper (init);
29240       bool id = (DECL_P (stripped_init)
29241 		 || ((TREE_CODE (init) == COMPONENT_REF
29242 		      || TREE_CODE (init) == SCOPE_REF)
29243 		     && !REF_PARENTHESIZED_P (init)));
29244       targs = make_tree_vec (1);
29245       TREE_VEC_ELT (targs, 0)
29246 	= finish_decltype_type (init, id, tf_warning_or_error);
29247       if (type != auto_node)
29248 	{
29249           if (complain & tf_error)
29250 	    error ("%qT as type rather than plain %<decltype(auto)%>", type);
29251 	  return error_mark_node;
29252 	}
29253     }
29254   else
29255     {
29256       if (error_operand_p (init))
29257 	return error_mark_node;
29258 
29259       tree parms = build_tree_list (NULL_TREE, type);
29260       tree tparms;
29261 
29262       if (flag_concepts)
29263 	tparms = extract_autos (type);
29264       else
29265 	{
29266 	  tparms = make_tree_vec (1);
29267 	  TREE_VEC_ELT (tparms, 0)
29268 	    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
29269 	}
29270 
29271       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
29272       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
29273 				       DEDUCE_CALL,
29274 				       NULL, /*explain_p=*/false);
29275       if (val > 0)
29276 	{
29277 	  if (processing_template_decl)
29278 	    /* Try again at instantiation time.  */
29279 	    return type;
29280 	  if (type && type != error_mark_node
29281 	      && (complain & tf_error))
29282 	    /* If type is error_mark_node a diagnostic must have been
29283 	       emitted by now.  Also, having a mention to '<type error>'
29284 	       in the diagnostic is not really useful to the user.  */
29285 	    {
29286 	      if (cfun
29287 		  && FNDECL_USED_AUTO (current_function_decl)
29288 		  && (auto_node
29289 		      == DECL_SAVED_AUTO_RETURN_TYPE (current_function_decl))
29290 		  && LAMBDA_FUNCTION_P (current_function_decl))
29291 		error ("unable to deduce lambda return type from %qE", init);
29292 	      else
29293 		error ("unable to deduce %qT from %qE", type, init);
29294 	      type_unification_real (tparms, targs, parms, &init, 1, 0,
29295 				     DEDUCE_CALL,
29296 				     NULL, /*explain_p=*/true);
29297 	    }
29298 	  return error_mark_node;
29299 	}
29300     }
29301 
29302   /* Check any placeholder constraints against the deduced type. */
29303   if (flag_concepts && !processing_template_decl)
29304     if (tree check = NON_ERROR (PLACEHOLDER_TYPE_CONSTRAINTS (auto_node)))
29305       {
29306         /* Use the deduced type to check the associated constraints. If we
29307            have a partial-concept-id, rebuild the argument list so that
29308            we check using the extra arguments. */
29309 	check = unpack_concept_check (check);
29310 	gcc_assert (TREE_CODE (check) == TEMPLATE_ID_EXPR);
29311 	tree cdecl = TREE_OPERAND (check, 0);
29312 	if (OVL_P (cdecl))
29313 	  cdecl = OVL_FIRST (cdecl);
29314         tree cargs = TREE_OPERAND (check, 1);
29315         if (TREE_VEC_LENGTH (cargs) > 1)
29316           {
29317             cargs = copy_node (cargs);
29318             TREE_VEC_ELT (cargs, 0) = TREE_VEC_ELT (targs, 0);
29319           }
29320         else
29321           cargs = targs;
29322 
29323 	/* Rebuild the check using the deduced arguments.  */
29324 	check = build_concept_check (cdecl, cargs, tf_none);
29325 
29326 	if (!constraints_satisfied_p (check))
29327           {
29328             if (complain & tf_warning_or_error)
29329               {
29330 		auto_diagnostic_group d;
29331                 switch (context)
29332                   {
29333                   case adc_unspecified:
29334 		  case adc_unify:
29335                     error("placeholder constraints not satisfied");
29336                     break;
29337                   case adc_variable_type:
29338 		  case adc_decomp_type:
29339                     error ("deduced initializer does not satisfy "
29340                            "placeholder constraints");
29341                     break;
29342                   case adc_return_type:
29343                     error ("deduced return type does not satisfy "
29344                            "placeholder constraints");
29345                     break;
29346                   case adc_requirement:
29347 		    error ("deduced expression type does not satisfy "
29348                            "placeholder constraints");
29349                     break;
29350                   }
29351 		diagnose_constraints (input_location, check, targs);
29352               }
29353             return error_mark_node;
29354           }
29355       }
29356 
29357   if (processing_template_decl && context != adc_unify)
29358     outer_targs = current_template_args ();
29359   targs = add_to_template_args (outer_targs, targs);
29360   return tsubst (type, targs, complain, NULL_TREE);
29361 }
29362 
29363 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
29364    result.  */
29365 
29366 tree
splice_late_return_type(tree type,tree late_return_type)29367 splice_late_return_type (tree type, tree late_return_type)
29368 {
29369   if (late_return_type)
29370     {
29371       gcc_assert (is_auto (type) || seen_error ());
29372       return late_return_type;
29373     }
29374 
29375   if (tree auto_node = find_type_usage (type, is_auto))
29376     if (TEMPLATE_TYPE_LEVEL (auto_node) <= processing_template_decl)
29377       {
29378 	/* In an abbreviated function template we didn't know we were dealing
29379 	   with a function template when we saw the auto return type, so rebuild
29380 	   the return type using an auto with the correct level.  */
29381 	tree new_auto = make_auto_1 (TYPE_IDENTIFIER (auto_node), false);
29382 	tree auto_vec = make_tree_vec (1);
29383 	TREE_VEC_ELT (auto_vec, 0) = new_auto;
29384 	tree targs = add_outermost_template_args (current_template_args (),
29385 						  auto_vec);
29386 	/* FIXME: We should also rebuild the constraint to refer to the new
29387 	   auto.  */
29388 	PLACEHOLDER_TYPE_CONSTRAINTS (new_auto)
29389 	  = PLACEHOLDER_TYPE_CONSTRAINTS (auto_node);
29390 	TYPE_CANONICAL (new_auto) = canonical_type_parameter (new_auto);
29391 	return tsubst (type, targs, tf_none, NULL_TREE);
29392       }
29393   return type;
29394 }
29395 
29396 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
29397    'decltype(auto)' or a deduced class template.  */
29398 
29399 bool
is_auto(const_tree type)29400 is_auto (const_tree type)
29401 {
29402   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
29403       && (TYPE_IDENTIFIER (type) == auto_identifier
29404 	  || TYPE_IDENTIFIER (type) == decltype_auto_identifier))
29405     return true;
29406   else
29407     return false;
29408 }
29409 
29410 /* for_each_template_parm callback for type_uses_auto.  */
29411 
29412 int
is_auto_r(tree tp,void *)29413 is_auto_r (tree tp, void */*data*/)
29414 {
29415   return is_auto (tp);
29416 }
29417 
29418 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
29419    a use of `auto'.  Returns NULL_TREE otherwise.  */
29420 
29421 tree
type_uses_auto(tree type)29422 type_uses_auto (tree type)
29423 {
29424   if (type == NULL_TREE)
29425     return NULL_TREE;
29426   else if (flag_concepts)
29427     {
29428       /* The Concepts TS allows multiple autos in one type-specifier; just
29429 	 return the first one we find, do_auto_deduction will collect all of
29430 	 them.  */
29431       if (uses_template_parms (type))
29432 	return for_each_template_parm (type, is_auto_r, /*data*/NULL,
29433 				       /*visited*/NULL, /*nondeduced*/false);
29434       else
29435 	return NULL_TREE;
29436     }
29437   else
29438     return find_type_usage (type, is_auto);
29439 }
29440 
29441 /* Report ill-formed occurrences of auto types in ARGUMENTS.  If
29442    concepts are enabled, auto is acceptable in template arguments, but
29443    only when TEMPL identifies a template class.  Return TRUE if any
29444    such errors were reported.  */
29445 
29446 bool
check_auto_in_tmpl_args(tree tmpl,tree args)29447 check_auto_in_tmpl_args (tree tmpl, tree args)
29448 {
29449   /* If there were previous errors, nevermind.  */
29450   if (!args || TREE_CODE (args) != TREE_VEC)
29451     return false;
29452 
29453   /* If TMPL is an identifier, we're parsing and we can't tell yet
29454      whether TMPL is supposed to be a type, a function or a variable.
29455      We'll only be able to tell during template substitution, so we
29456      expect to be called again then.  If concepts are enabled and we
29457      know we have a type, we're ok.  */
29458   if (flag_concepts
29459       && (identifier_p (tmpl)
29460 	  || (DECL_P (tmpl)
29461 	      &&  (DECL_TYPE_TEMPLATE_P (tmpl)
29462 		   || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)))))
29463     return false;
29464 
29465   /* Quickly search for any occurrences of auto; usually there won't
29466      be any, and then we'll avoid allocating the vector.  */
29467   if (!type_uses_auto (args))
29468     return false;
29469 
29470   bool errors = false;
29471 
29472   tree vec = extract_autos (args);
29473   for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
29474     {
29475       tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
29476       error_at (DECL_SOURCE_LOCATION (xauto),
29477 		"invalid use of %qT in template argument", xauto);
29478       errors = true;
29479     }
29480 
29481   return errors;
29482 }
29483 
29484 /* For a given template T, return the vector of typedefs referenced
29485    in T for which access check is needed at T instantiation time.
29486    T is either  a FUNCTION_DECL or a RECORD_TYPE.
29487    Those typedefs were added to T by the function
29488    append_type_to_template_for_access_check.  */
29489 
29490 vec<qualified_typedef_usage_t, va_gc> *
get_types_needing_access_check(tree t)29491 get_types_needing_access_check (tree t)
29492 {
29493   tree ti;
29494   vec<qualified_typedef_usage_t, va_gc> *result = NULL;
29495 
29496   if (!t || t == error_mark_node)
29497     return NULL;
29498 
29499   if (!(ti = get_template_info (t)))
29500     return NULL;
29501 
29502   if (CLASS_TYPE_P (t)
29503       || TREE_CODE (t) == FUNCTION_DECL)
29504     {
29505       if (!TI_TEMPLATE (ti))
29506 	return NULL;
29507 
29508       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
29509     }
29510 
29511   return result;
29512 }
29513 
29514 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
29515    tied to T. That list of typedefs will be access checked at
29516    T instantiation time.
29517    T is either a FUNCTION_DECL or a RECORD_TYPE.
29518    TYPE_DECL is a TYPE_DECL node representing a typedef.
29519    SCOPE is the scope through which TYPE_DECL is accessed.
29520    LOCATION is the location of the usage point of TYPE_DECL.
29521 
29522    This function is a subroutine of
29523    append_type_to_template_for_access_check.  */
29524 
29525 static void
append_type_to_template_for_access_check_1(tree t,tree type_decl,tree scope,location_t location)29526 append_type_to_template_for_access_check_1 (tree t,
29527 					    tree type_decl,
29528 					    tree scope,
29529 					    location_t location)
29530 {
29531   qualified_typedef_usage_t typedef_usage;
29532   tree ti;
29533 
29534   if (!t || t == error_mark_node)
29535     return;
29536 
29537   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
29538 	       || CLASS_TYPE_P (t))
29539 	      && type_decl
29540 	      && TREE_CODE (type_decl) == TYPE_DECL
29541 	      && scope);
29542 
29543   if (!(ti = get_template_info (t)))
29544     return;
29545 
29546   gcc_assert (TI_TEMPLATE (ti));
29547 
29548   typedef_usage.typedef_decl = type_decl;
29549   typedef_usage.context = scope;
29550   typedef_usage.locus = location;
29551 
29552   vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
29553 }
29554 
29555 /* Append TYPE_DECL to the template TEMPL.
29556    TEMPL is either a class type, a FUNCTION_DECL or a TEMPLATE_DECL.
29557    At TEMPL instanciation time, TYPE_DECL will be checked to see
29558    if it can be accessed through SCOPE.
29559    LOCATION is the location of the usage point of TYPE_DECL.
29560 
29561    e.g. consider the following code snippet:
29562 
29563      class C
29564      {
29565        typedef int myint;
29566      };
29567 
29568      template<class U> struct S
29569      {
29570        C::myint mi; // <-- usage point of the typedef C::myint
29571      };
29572 
29573      S<char> s;
29574 
29575    At S<char> instantiation time, we need to check the access of C::myint
29576    In other words, we need to check the access of the myint typedef through
29577    the C scope. For that purpose, this function will add the myint typedef
29578    and the scope C through which its being accessed to a list of typedefs
29579    tied to the template S. That list will be walked at template instantiation
29580    time and access check performed on each typedefs it contains.
29581    Note that this particular code snippet should yield an error because
29582    myint is private to C.  */
29583 
29584 void
append_type_to_template_for_access_check(tree templ,tree type_decl,tree scope,location_t location)29585 append_type_to_template_for_access_check (tree templ,
29586                                           tree type_decl,
29587 					  tree scope,
29588 					  location_t location)
29589 {
29590   qualified_typedef_usage_t *iter;
29591   unsigned i;
29592 
29593   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
29594 
29595   /* Make sure we don't append the type to the template twice.  */
29596   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
29597     if (iter->typedef_decl == type_decl && scope == iter->context)
29598       return;
29599 
29600   append_type_to_template_for_access_check_1 (templ, type_decl,
29601 					      scope, location);
29602 }
29603 
29604 /* Recursively walk over && expressions searching for EXPR. Return a reference
29605    to that expression.  */
29606 
find_template_requirement(tree * t,tree key)29607 static tree *find_template_requirement (tree *t, tree key)
29608 {
29609   if (*t == key)
29610     return t;
29611   if (TREE_CODE (*t) == TRUTH_ANDIF_EXPR)
29612     {
29613       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 0), key))
29614 	return p;
29615       if (tree *p = find_template_requirement (&TREE_OPERAND (*t, 1), key))
29616 	return p;
29617     }
29618   return 0;
29619 }
29620 
29621 /* Convert the generic type parameters in PARM that match the types given in the
29622    range [START_IDX, END_IDX) from the current_template_parms into generic type
29623    packs.  */
29624 
29625 tree
convert_generic_types_to_packs(tree parm,int start_idx,int end_idx)29626 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
29627 {
29628   tree current = current_template_parms;
29629   int depth = TMPL_PARMS_DEPTH (current);
29630   current = INNERMOST_TEMPLATE_PARMS (current);
29631   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
29632 
29633   for (int i = 0; i < start_idx; ++i)
29634     TREE_VEC_ELT (replacement, i)
29635       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
29636 
29637   for (int i = start_idx; i < end_idx; ++i)
29638     {
29639       /* Create a distinct parameter pack type from the current parm and add it
29640 	 to the replacement args to tsubst below into the generic function
29641 	 parameter.  */
29642       tree node = TREE_VEC_ELT (current, i);
29643       tree o = TREE_TYPE (TREE_VALUE (node));
29644       tree t = copy_type (o);
29645       TEMPLATE_TYPE_PARM_INDEX (t)
29646 	= reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
29647 				      t, 0, 0, tf_none);
29648       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
29649       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
29650       TYPE_MAIN_VARIANT (t) = t;
29651       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
29652       TYPE_CANONICAL (t) = canonical_type_parameter (t);
29653       TREE_VEC_ELT (replacement, i) = t;
29654 
29655       /* Replace the current template parameter with new pack.  */
29656       TREE_VALUE (node) = TREE_CHAIN (t);
29657 
29658       /* Surgically adjust the associated constraint of adjusted parameter
29659          and it's corresponding contribution to the current template
29660          requirements.  */
29661       if (tree constr = TEMPLATE_PARM_CONSTRAINTS (node))
29662 	{
29663 	  tree id = unpack_concept_check (constr);
29664 	  TREE_VEC_ELT (TREE_OPERAND (id, 1), 0) = t;
29665 	  tree fold = finish_left_unary_fold_expr (constr, TRUTH_ANDIF_EXPR);
29666 	  TEMPLATE_PARM_CONSTRAINTS (node) = fold;
29667 
29668 	  /* If there was a constraint, we also need to replace that in
29669 	     the template requirements, which we've already built.  */
29670 	  tree *reqs = &TEMPLATE_PARMS_CONSTRAINTS (current_template_parms);
29671 	  reqs = find_template_requirement (reqs, constr);
29672 	  *reqs = fold;
29673 	}
29674     }
29675 
29676   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
29677     TREE_VEC_ELT (replacement, i)
29678       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
29679 
29680   /* If there are more levels then build up the replacement with the outer
29681      template parms.  */
29682   if (depth > 1)
29683     replacement = add_to_template_args (template_parms_to_args
29684 					(TREE_CHAIN (current_template_parms)),
29685 					replacement);
29686 
29687   return tsubst (parm, replacement, tf_none, NULL_TREE);
29688 }
29689 
29690 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
29691    0..N-1.  */
29692 
29693 void
declare_integer_pack(void)29694 declare_integer_pack (void)
29695 {
29696   tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
29697 			       build_function_type_list (integer_type_node,
29698 							 integer_type_node,
29699 							 NULL_TREE),
29700 			       NULL_TREE, ECF_CONST);
29701   DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
29702   set_decl_built_in_function (ipfn, BUILT_IN_FRONTEND,
29703 			      CP_BUILT_IN_INTEGER_PACK);
29704 }
29705 
29706 /* Set up the hash tables for template instantiations.  */
29707 
29708 void
init_template_processing(void)29709 init_template_processing (void)
29710 {
29711   /* FIXME: enable sanitization (PR87847) */
29712   decl_specializations = hash_table<spec_hasher>::create_ggc (37, false);
29713   type_specializations = hash_table<spec_hasher>::create_ggc (37, false);
29714 
29715   if (cxx_dialect >= cxx11)
29716     declare_integer_pack ();
29717 }
29718 
29719 /* Print stats about the template hash tables for -fstats.  */
29720 
29721 void
print_template_statistics(void)29722 print_template_statistics (void)
29723 {
29724   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
29725 	   "%f collisions\n", (long) decl_specializations->size (),
29726 	   (long) decl_specializations->elements (),
29727 	   decl_specializations->collisions ());
29728   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
29729 	   "%f collisions\n", (long) type_specializations->size (),
29730 	   (long) type_specializations->elements (),
29731 	   type_specializations->collisions ());
29732 }
29733 
29734 #if CHECKING_P
29735 
29736 namespace selftest {
29737 
29738 /* Verify that build_non_dependent_expr () works, for various expressions,
29739    and that location wrappers don't affect the results.  */
29740 
29741 static void
test_build_non_dependent_expr()29742 test_build_non_dependent_expr ()
29743 {
29744   location_t loc = BUILTINS_LOCATION;
29745 
29746   /* Verify constants, without and with location wrappers.  */
29747   tree int_cst = build_int_cst (integer_type_node, 42);
29748   ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
29749 
29750   tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
29751   ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
29752   ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
29753 
29754   tree string_lit = build_string (4, "foo");
29755   TREE_TYPE (string_lit) = char_array_type_node;
29756   string_lit = fix_string_type (string_lit);
29757   ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
29758 
29759   tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
29760   ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
29761   ASSERT_EQ (wrapped_string_lit,
29762 	     build_non_dependent_expr (wrapped_string_lit));
29763 }
29764 
29765 /* Verify that type_dependent_expression_p () works correctly, even
29766    in the presence of location wrapper nodes.  */
29767 
29768 static void
test_type_dependent_expression_p()29769 test_type_dependent_expression_p ()
29770 {
29771   location_t loc = BUILTINS_LOCATION;
29772 
29773   tree name = get_identifier ("foo");
29774 
29775   /* If no templates are involved, nothing is type-dependent.  */
29776   gcc_assert (!processing_template_decl);
29777   ASSERT_FALSE (type_dependent_expression_p (name));
29778 
29779   ++processing_template_decl;
29780 
29781   /* Within a template, an unresolved name is always type-dependent.  */
29782   ASSERT_TRUE (type_dependent_expression_p (name));
29783 
29784   /* Ensure it copes with NULL_TREE and errors.  */
29785   ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
29786   ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
29787 
29788   /* A USING_DECL in a template should be type-dependent, even if wrapped
29789      with a location wrapper (PR c++/83799).  */
29790   tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
29791   TREE_TYPE (using_decl) = integer_type_node;
29792   ASSERT_TRUE (type_dependent_expression_p (using_decl));
29793   tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
29794   ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
29795   ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
29796 
29797   --processing_template_decl;
29798 }
29799 
29800 /* Run all of the selftests within this file.  */
29801 
29802 void
cp_pt_c_tests()29803 cp_pt_c_tests ()
29804 {
29805   test_build_non_dependent_expr ();
29806   test_type_dependent_expression_p ();
29807 }
29808 
29809 } // namespace selftest
29810 
29811 #endif /* #if CHECKING_P */
29812 
29813 #include "gt-cp-pt.h"
29814